lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
066e3b7421f56462948712d346c2445c64f09572
| 0 |
javamelody/javamelody,javamelody/javamelody,javamelody/javamelody
|
/*
* Copyright 2008-2017 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bull.javamelody;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
/**
* Rapport html pour afficher un fichier source java.
* @author Emeric Vernat
*/
class HtmlSourceReport extends HtmlAbstractReport {
private static final String MAVEN_CENTRAL = "http://repo1.maven.org/maven2";
private static final File LOCAL_REPO = new File(
System.getProperty("user.home") + "/.m2/repository");
private static final File JDK_SRC_FILE = getJdkSrcFile();
private final String source;
HtmlSourceReport(String className, Writer writer) throws IOException {
super(writer);
if (className.indexOf('$') == -1) {
this.source = getSource(className);
} else {
this.source = getSource(className.substring(0, className.indexOf('$')));
}
}
private String getSource(String className) throws IOException {
final Class<?> clazz;
try {
clazz = Class.forName(className);
} catch (final ClassNotFoundException e) {
return null;
}
if (clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax.")
&& clazz.getProtectionDomain().getCodeSource() == null) {
if (JDK_SRC_FILE != null) {
return getSourceFromJar(clazz, JDK_SRC_FILE);
}
return null;
}
return getSourceFromMavenRepo(clazz);
}
private static File getJdkSrcFile() {
File file = new File(System.getProperty("java.home"));
if ("jre".equalsIgnoreCase(file.getName())) {
file = file.getParentFile();
}
final File srcZipFile = new File(file, "src.zip");
if (srcZipFile.exists()) {
return srcZipFile;
}
return null;
}
private String getSourceFromJar(Class<?> clazz, File srcJarFile)
throws ZipException, IOException {
final ZipFile zipFile = new ZipFile(srcJarFile);
try {
final ZipEntry entry = zipFile.getEntry(clazz.getName().replace('.', '/') + ".java");
if (entry == null) {
return null;
}
final StringWriter writer = new StringWriter();
final InputStream inputStream = zipFile.getInputStream(entry);
try {
final Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
final char[] chars = new char[1024];
int read = reader.read(chars);
while (read != -1) {
writer.write(chars, 0, read);
read = reader.read(chars);
}
} finally {
inputStream.close();
}
return writer.toString();
} finally {
zipFile.close();
}
}
private String getSourceFromMavenRepo(Class<?> clazz) throws IOException {
final Map<String, String> mavenCoordinates = getMavenCoordinates(clazz);
if (mavenCoordinates == null) {
return null;
}
final String groupId = mavenCoordinates.get("groupId");
final String artifactId = mavenCoordinates.get("artifactId");
final String version = mavenCoordinates.get("version");
final File storageDirectory = Parameters
.getStorageDirectory(Parameters.getCurrentApplication());
final File srcJarFile = new File(storageDirectory,
"sources/" + artifactId + '-' + version + "-sources.jar");
if (!srcJarFile.exists() || srcJarFile.length() == 0) {
for (final String mavenRepository : getMavenRepositories()) {
final String url = mavenRepository + '/' + groupId.replace('.', '/') + '/'
+ artifactId + '/' + version + '/' + artifactId + '-' + version
+ "-sources.jar";
if (!url.startsWith("http") && new File(url).exists()) {
return getSourceFromJar(clazz, new File(url));
}
final URL sourceUrl = new URL(url);
srcJarFile.getParentFile().mkdirs();
final OutputStream output = new FileOutputStream(srcJarFile);
try {
final LabradorRetriever labradorRetriever = new LabradorRetriever(sourceUrl);
labradorRetriever.downloadTo(output);
// si trouvé, on arrête
break;
} catch (final IOException e) {
output.close();
srcJarFile.delete();
// si non trouvé, on continue avec le repo suivant s'il y en a un
} finally {
output.close();
}
}
}
if (srcJarFile.exists()) {
return getSourceFromJar(clazz, srcJarFile);
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<String, String> getMavenCoordinates(Class<?> clazz) throws IOException {
final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
if (codeSource == null) {
return null;
}
final URL location = codeSource.getLocation();
final ZipInputStream zipInputStream = new ZipInputStream(
new BufferedInputStream(location.openStream(), 4096));
try {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (entry.getName().startsWith("META-INF/")
&& entry.getName().endsWith("/pom.properties")) {
final Properties properties = new Properties();
properties.load(zipInputStream);
return new HashMap<String, String>((Map) properties);
}
zipInputStream.closeEntry();
entry = zipInputStream.getNextEntry();
}
} finally {
zipInputStream.close();
}
return null;
}
private List<String> getMavenRepositories() {
final String parameter = Parameters.getParameter(Parameter.MAVEN_REPOSITORIES);
if (parameter != null) {
final List<String> result = new ArrayList<String>();
for (final String repo : parameter.split(",")) {
result.add(repo.trim());
}
return result;
}
return Arrays.asList(LOCAL_REPO.getPath(), MAVEN_CENTRAL);
}
@Override
void toHtml() throws IOException {
if (source != null) {
String html = JavaHTMLizer.htmlize(source);
html = JavaHTMLizer.addLineNumbers(html);
writeDirectly("<code>");
writeDirectly(html);
writeDirectly("</code>");
} else {
write("#source_not_found#");
}
}
static String htmlEncodeStackTraceElement(String element) {
if (element.endsWith(")") && !element.endsWith("(Native Method)")
&& !element.endsWith("(Unknown Source)")) {
final int index3 = element.lastIndexOf(':');
final int index2 = element.lastIndexOf('(');
final int index1 = element.lastIndexOf('.', index2);
final int index0 = element.lastIndexOf(' ', index1);
if (index1 > index0 && index2 != -1 && index3 > index2) {
final String classNameEncoded = urlEncode(element.substring(index0 + 1, index1));
return htmlEncodeButNotSpace(element.substring(0, index2 + 1)) + "<a href='?part="
+ HttpParameters.SOURCE_PART + "&class=" + classNameEncoded + '#'
+ urlEncode(element.substring(index3 + 1, element.length() - 1))
+ "' class='lightwindow' type='external' title='" + classNameEncoded + "'>"
+ htmlEncode(element.substring(index2 + 1, element.length() - 1)) + "</a>)";
}
}
return htmlEncodeButNotSpace(element);
}
static String addLinkToClassName(String className) {
String cleanClassName = className;
if (cleanClassName.endsWith("[]")) {
cleanClassName = cleanClassName.substring(0, cleanClassName.length() - 2);
}
return "<a href='?part=" + HttpParameters.SOURCE_PART + "&class=" + cleanClassName
+ "' class='lightwindow' type='external' title='" + cleanClassName + "'>"
+ className + "</a>";
}
}
|
javamelody-core/src/main/java/net/bull/javamelody/HtmlSourceReport.java
|
/*
* Copyright 2008-2017 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bull.javamelody;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
/**
* Rapport html pour afficher un fichier source java.
* @author Emeric Vernat
*/
class HtmlSourceReport extends HtmlAbstractReport {
private static final String MAVEN_CENTRAL = "http://repo1.maven.org/maven2";
private static final File JDK_SRC_FILE = getJdkSrcFile();
private final String source;
HtmlSourceReport(String className, Writer writer) throws IOException {
super(writer);
if (className.indexOf('$') == -1) {
this.source = getSource(className);
} else {
this.source = getSource(className.substring(0, className.indexOf('$')));
}
}
private String getSource(String className) throws IOException {
final Class<?> clazz;
try {
clazz = Class.forName(className);
} catch (final ClassNotFoundException e) {
return null;
}
if (clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax.")
&& clazz.getProtectionDomain().getCodeSource() == null) {
if (JDK_SRC_FILE != null) {
return getSourceFromJar(clazz, JDK_SRC_FILE);
}
return null;
}
return getSourceFromMavenRepo(clazz);
}
private static File getJdkSrcFile() {
File file = new File(System.getProperty("java.home"));
if ("jre".equalsIgnoreCase(file.getName())) {
file = file.getParentFile();
}
final File srcZipFile = new File(file, "src.zip");
if (srcZipFile.exists()) {
return srcZipFile;
}
return null;
}
private String getSourceFromJar(Class<?> clazz, File srcJarFile)
throws ZipException, IOException {
final ZipFile zipFile = new ZipFile(srcJarFile);
try {
final ZipEntry entry = zipFile.getEntry(clazz.getName().replace('.', '/') + ".java");
if (entry == null) {
return null;
}
final StringWriter writer = new StringWriter();
final InputStream inputStream = zipFile.getInputStream(entry);
try {
final Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
final char[] chars = new char[1024];
int read = reader.read(chars);
while (read != -1) {
writer.write(chars, 0, read);
read = reader.read(chars);
}
} finally {
inputStream.close();
}
return writer.toString();
} finally {
zipFile.close();
}
}
private String getSourceFromMavenRepo(Class<?> clazz) throws IOException {
final Map<String, String> mavenCoordinates = getMavenCoordinates(clazz);
if (mavenCoordinates == null) {
return null;
}
final String groupId = mavenCoordinates.get("groupId");
final String artifactId = mavenCoordinates.get("artifactId");
final String version = mavenCoordinates.get("version");
final File storageDirectory = Parameters
.getStorageDirectory(Parameters.getCurrentApplication());
final File srcJarFile = new File(storageDirectory,
"sources/" + artifactId + '-' + version + "-sources.jar");
if (!srcJarFile.exists() || srcJarFile.length() == 0) {
for (final String mavenRepository : getMavenRepositories()) {
final URL sourceUrl = new URL(
mavenRepository + '/' + groupId.replace('.', '/') + '/' + artifactId + '/'
+ version + '/' + artifactId + '-' + version + "-sources.jar");
srcJarFile.getParentFile().mkdirs();
final OutputStream output = new FileOutputStream(srcJarFile);
try {
final LabradorRetriever labradorRetriever = new LabradorRetriever(sourceUrl);
labradorRetriever.downloadTo(output);
// si trouvé, on arrête
break;
} catch (final IOException e) {
output.close();
srcJarFile.delete();
// si non trouvé, on continue avec le repo suivant s'il y en a un
} finally {
output.close();
}
}
}
if (srcJarFile.exists()) {
return getSourceFromJar(clazz, srcJarFile);
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<String, String> getMavenCoordinates(Class<?> clazz) throws IOException {
final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
if (codeSource == null) {
return null;
}
final URL location = codeSource.getLocation();
final ZipInputStream zipInputStream = new ZipInputStream(
new BufferedInputStream(location.openStream(), 4096));
try {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (entry.getName().startsWith("META-INF/")
&& entry.getName().endsWith("/pom.properties")) {
final Properties properties = new Properties();
properties.load(zipInputStream);
return new HashMap<String, String>((Map) properties);
}
zipInputStream.closeEntry();
entry = zipInputStream.getNextEntry();
}
} finally {
zipInputStream.close();
}
return null;
}
private List<String> getMavenRepositories() {
final String parameter = Parameters.getParameter(Parameter.MAVEN_REPOSITORIES);
if (parameter != null) {
final List<String> result = new ArrayList<String>();
for (final String repo : parameter.split(",")) {
result.add(repo.trim());
}
return result;
}
return Collections.singletonList(MAVEN_CENTRAL);
}
@Override
void toHtml() throws IOException {
if (source != null) {
String html = JavaHTMLizer.htmlize(source);
html = JavaHTMLizer.addLineNumbers(html);
writeDirectly("<code>");
writeDirectly(html);
writeDirectly("</code>");
} else {
write("#source_not_found#");
}
}
static String htmlEncodeStackTraceElement(String element) {
if (element.endsWith(")") && !element.endsWith("(Native Method)")
&& !element.endsWith("(Unknown Source)")) {
final int index3 = element.lastIndexOf(':');
final int index2 = element.lastIndexOf('(');
final int index1 = element.lastIndexOf('.', index2);
final int index0 = element.lastIndexOf(' ', index1);
if (index1 > index0 && index2 != -1 && index3 > index2) {
final String classNameEncoded = urlEncode(element.substring(index0 + 1, index1));
return htmlEncodeButNotSpace(element.substring(0, index2 + 1)) + "<a href='?part="
+ HttpParameters.SOURCE_PART + "&class=" + classNameEncoded + '#'
+ urlEncode(element.substring(index3 + 1, element.length() - 1))
+ "' class='lightwindow' type='external' title='" + classNameEncoded + "'>"
+ htmlEncode(element.substring(index2 + 1, element.length() - 1)) + "</a>)";
}
}
return htmlEncodeButNotSpace(element);
}
static String addLinkToClassName(String className) {
String cleanClassName = className;
if (cleanClassName.endsWith("[]")) {
cleanClassName = cleanClassName.substring(0, cleanClassName.length() - 2);
}
return "<a href='?part=" + HttpParameters.SOURCE_PART + "&class=" + cleanClassName
+ "' class='lightwindow' type='external' title='" + cleanClassName + "'>"
+ className + "</a>";
}
}
|
add source search in local repo
|
javamelody-core/src/main/java/net/bull/javamelody/HtmlSourceReport.java
|
add source search in local repo
|
<ide><path>avamelody-core/src/main/java/net/bull/javamelody/HtmlSourceReport.java
<ide> import java.nio.charset.Charset;
<ide> import java.security.CodeSource;
<ide> import java.util.ArrayList;
<del>import java.util.Collections;
<add>import java.util.Arrays;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> */
<ide> class HtmlSourceReport extends HtmlAbstractReport {
<ide> private static final String MAVEN_CENTRAL = "http://repo1.maven.org/maven2";
<add>
<add> private static final File LOCAL_REPO = new File(
<add> System.getProperty("user.home") + "/.m2/repository");
<ide>
<ide> private static final File JDK_SRC_FILE = getJdkSrcFile();
<ide>
<ide> "sources/" + artifactId + '-' + version + "-sources.jar");
<ide> if (!srcJarFile.exists() || srcJarFile.length() == 0) {
<ide> for (final String mavenRepository : getMavenRepositories()) {
<del> final URL sourceUrl = new URL(
<del> mavenRepository + '/' + groupId.replace('.', '/') + '/' + artifactId + '/'
<del> + version + '/' + artifactId + '-' + version + "-sources.jar");
<add> final String url = mavenRepository + '/' + groupId.replace('.', '/') + '/'
<add> + artifactId + '/' + version + '/' + artifactId + '-' + version
<add> + "-sources.jar";
<add> if (!url.startsWith("http") && new File(url).exists()) {
<add> return getSourceFromJar(clazz, new File(url));
<add> }
<add> final URL sourceUrl = new URL(url);
<ide> srcJarFile.getParentFile().mkdirs();
<ide> final OutputStream output = new FileOutputStream(srcJarFile);
<ide> try {
<ide> }
<ide> return result;
<ide> }
<del> return Collections.singletonList(MAVEN_CENTRAL);
<add> return Arrays.asList(LOCAL_REPO.getPath(), MAVEN_CENTRAL);
<ide> }
<ide>
<ide> @Override
|
|
Java
|
apache-2.0
|
25f22cf500a91161b998e13548686fd232691c6c
| 0 |
spatialsimulator/XitoSBML,spatialsimulator/XitoSBML,spatialsimulator/XitoSBML
|
package jp.ac.keio.bio.fun.xitosbml;
import ij.IJ;
import ij.ImageJ;
import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial;
/**
* The Class Spatial_Img_SBML.
* This class has several methods which will be able to launch from * 'Plugins' -> 'XitoSBML'.
* List of ImageJ plugins which XitoSBML provieds is described in src/main/resources/plugins.config.
*/
public class Spatial_Img_SBML extends Spatial_SBML {
/**
* Launch XitoSBML as ImageJ plugin.
* List of ImageJ plugins which XitoSBML provieds is described in src/main/resources/plugins.config.
*/
public void run(String args) {
if (args.equals("about")) {
showAbout();
return;
} else {
new MainImgSpatial().run(args);
}
}
/**
* Display "About" message
*/
public void showAbout() {
IJ.showMessage("XitoSBML",
"XitoSBML " + this.version + ": Spatial SBML Plugin for ImageJ\n"
+ "Copyright (C) 2014-2019 Funahashi Lab. Keio University.\n \n"
+ "XitoSBML is an ImageJ plugin which creates Spatial SBML model\n"
+ "from segmented images. XitoSBML is not just a converter,\n"
+ "but also a spatial model editor so that users can add\n"
+ "molecules(species), reactions and advection/diffusion coefficients\n"
+ "to the converted Spatial SBML model.\n"
+ "More information is available at\n \n"
+ " "+"https://github.com/spatialsimulator/XitoSBML"
);
}
/**
* Example main() method which will launch ImageJ and call XitoSBML.
* @param args
*/
public static void main(String[] args) {
// set the plugins.dir property to make the plugin appear in the Plugins menu
Class<?> clazz = Spatial_Img_SBML.class;
String url = clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class").toString();
String pluginsDir = url.substring("file:".length(), url.length() - clazz.getName().length() - ".class".length());
System.setProperty("plugins.dir", pluginsDir);
// start ImageJ
new ImageJ();
// run the plugin
IJ.runPlugIn(clazz.getName(), "");
}
}
|
src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Img_SBML.java
|
package jp.ac.keio.bio.fun.xitosbml;
import ij.IJ;
import ij.ImageJ;
import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial;
// TODO: Auto-generated Javadoc
/**
* The Class Spatial_Img_SBML.
*/
public class Spatial_Img_SBML extends Spatial_SBML {
/* (non-Javadoc)
* @see sbmlplugin.Spatial_SBML#run(java.lang.String)
*/
public void run(String args) {
if (args.equals("about")) {
showAbout();
return;
} else {
new MainImgSpatial().run(args);
}
}
public void showAbout() {
IJ.showMessage("XitoSBML",
"XitoSBML " + this.version + ": Spatial SBML Plugin for ImageJ\n"
+ "Copyright (C) 2014-2017 Funahashi Lab. Keio University.\n \n"
+ "XitoSBML is an ImageJ plugin which creates Spatial SBML model\n"
+ "from segmented images. XitoSBML is not just a converter,\n"
+ "but also a spatial model editor so that users can add\n"
+ "molecules(species), reactions and advection/diffusion coefficients\n"
+ "to the converted Spatial SBML model.\n"
+ "More information is available at\n \n"
+ " "+"https://github.com/spatialsimulator/XitoSBML"
);
}
public static void main(String[] args) {
// set the plugins.dir property to make the plugin appear in the Plugins menu
Class<?> clazz = Spatial_Img_SBML.class;
String url = clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class").toString();
String pluginsDir = url.substring("file:".length(), url.length() - clazz.getName().length() - ".class".length());
System.setProperty("plugins.dir", pluginsDir);
// start ImageJ
new ImageJ();
// run the plugin
IJ.runPlugIn(clazz.getName(), "");
}
}
|
Add comments.
|
src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Img_SBML.java
|
Add comments.
|
<ide><path>rc/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Img_SBML.java
<ide> import ij.ImageJ;
<ide> import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial;
<ide>
<del>// TODO: Auto-generated Javadoc
<ide> /**
<ide> * The Class Spatial_Img_SBML.
<add> * This class has several methods which will be able to launch from * 'Plugins' -> 'XitoSBML'.
<add> * List of ImageJ plugins which XitoSBML provieds is described in src/main/resources/plugins.config.
<ide> */
<ide> public class Spatial_Img_SBML extends Spatial_SBML {
<ide>
<del> /* (non-Javadoc)
<del> * @see sbmlplugin.Spatial_SBML#run(java.lang.String)
<del> */
<add> /**
<add> * Launch XitoSBML as ImageJ plugin.
<add> * List of ImageJ plugins which XitoSBML provieds is described in src/main/resources/plugins.config.
<add> */
<ide> public void run(String args) {
<ide> if (args.equals("about")) {
<ide> showAbout();
<ide> }
<ide> }
<ide>
<add> /**
<add> * Display "About" message
<add> */
<ide> public void showAbout() {
<ide> IJ.showMessage("XitoSBML",
<ide> "XitoSBML " + this.version + ": Spatial SBML Plugin for ImageJ\n"
<del> + "Copyright (C) 2014-2017 Funahashi Lab. Keio University.\n \n"
<add> + "Copyright (C) 2014-2019 Funahashi Lab. Keio University.\n \n"
<ide> + "XitoSBML is an ImageJ plugin which creates Spatial SBML model\n"
<ide> + "from segmented images. XitoSBML is not just a converter,\n"
<ide> + "but also a spatial model editor so that users can add\n"
<ide> );
<ide> }
<ide>
<add> /**
<add> * Example main() method which will launch ImageJ and call XitoSBML.
<add> * @param args
<add> */
<ide> public static void main(String[] args) {
<ide> // set the plugins.dir property to make the plugin appear in the Plugins menu
<ide> Class<?> clazz = Spatial_Img_SBML.class;
|
|
JavaScript
|
mit
|
06fd68c624bc9a86be6bfc48f79effabae908f33
| 0 |
vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb
|
Type.registerNamespace("ExoWeb.Model");
(function() {
function execute() {
var evalAffectsScope = false;
eval("evalAffectsScope = true;");
var undefined;
var log = ExoWeb.trace.log;
var throwAndLog = ExoWeb.trace.throwAndLog;
var disableConstruction = false;
//////////////////////////////////////////////////////////////////////////////////////
function Model() {
this._types = {};
this._validatingQueue = new EventQueue(
function(e) {
var meta = e.sender;
var issues = meta._propertyIssues[e.propName];
meta._raiseEvent("propertyValidating:" + e.propName, [meta, e.propName])
},
function(a, b) {
return a.sender == b.sender && a.propName == b.propName;
}
);
this._validatedQueue = new EventQueue(
function(e) {
var meta = e.sender;
var propName = e.property;
var issues = meta._propertyIssues[propName];
meta._raiseEvent("propertyValidated:" + propName, [meta, issues ? issues : []])
},
function(a, b) {
return a.sender == b.sender && a.property == b.property;
}
);
}
Model.property = function(path, thisType) {
var part = path.split(".");
var firstStep = parsePropertyStep(part[0]);
var isGlobal = firstStep.property !== "this";
var type;
if (isGlobal) {
// locate first model type
for (var t = window[Array.dequeue(part)]; t && part.length > 0; t = t[Array.dequeue(part)]) {
if (t.meta) {
type = t.meta;
break;
}
}
if (!type)
throwAndLog(["model"], "Invalid property path: {0}", [path]);
}
else {
if (firstStep.cast) {
type = window[firstStep.cast];
if (!type)
throwAndLog("model", "Path '{0}' references an unknown type: {1}", [path, firstStep.cast]);
type = type.meta;
}
else if (thisType instanceof Function)
type = thisType.meta;
else
type = thisType;
Array.dequeue(part);
}
return new PropertyChain(type, part);
}
Model.prototype = {
addType: function Model$addType(name, base) {
return this._types[name] = new Type(this, name, base);
},
beginValidation: function Model$beginValidation() {
this._validatingQueue.startQueueing();
this._validatedQueue.startQueueing();
},
endValidation: function Model$endValidation() {
this._validatingQueue.stopQueueing();
this._validatedQueue.stopQueueing();
},
type: function(name) {
return this._types[name];
},
addAfterPropertySet: function(handler) {
this._addEvent("afterPropertySet", handler);
},
notifyAfterPropertySet: function(obj, property, newVal, oldVal) {
this._raiseEvent("afterPropertySet", [obj, property, newVal, oldVal]);
},
addObjectRegistered: function(func) {
this._addEvent("objectRegistered", func);
},
notifyObjectRegistered: function(obj) {
this._raiseEvent("objectRegistered", [obj]);
},
addObjectUnregistered: function(func) {
this._addEvent("objectUnregistered", func);
},
notifyObjectUnregistered: function(obj) {
this._raiseEvent("objectUnregistered", [obj]);
},
addListChanged: function(func) {
this._addEvent("listChanged", func);
},
notifyListChanged: function(obj, property, changes) {
this._raiseEvent("listChanged", [obj, property, changes]);
}
}
Model.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.Model = Model;
Model.registerClass("ExoWeb.Model.Model");
//////////////////////////////////////////////////////////////////////////////////////
function Entity() {
}
Entity.mixin({
toString: function Entity$toString(formatName) {
var format;
if (formatName) {
format = this.constructor.formats[formatName];
if (!format)
throwAndLog(["formatting"], "Invalid format: {0}", arguments);
} else
format = this.constructor.formats.$display || this.constructor.formats.$system;
return format.convert(this);
}
});
Entity.formats = {
$system: new Format({
undefinedString: "",
nullString: "null",
convert: function(obj) {
return $format("{0}|{1}", [obj.meta.type.get_fullName(), obj.meta.id]);
},
convertBack: function(str) {
// indicates "no value", which is distinct from "no selection"
var ids = str.split("|");
var ctor = window[ids[0]];
if (ctor)
return ctor.get(ids[1]);
}
})
}
ExoWeb.Model.Entity = Entity;
Entity.registerClass("ExoWeb.Model.Entity");
//////////////////////////////////////////////////////////////////////////////////////
function Type(model, name, baseType) {
this._rules = {};
this._fullName = name;
this._pool = {};
this._legacyPool = {};
this._counter = 0;
this._properties = {};
this._model = model;
// generate class and constructor
var type = this;
var jstype = window[name];
if (jstype)
throwAndLog(["model"], "'{1}' has already been declared", arguments)
function construct(id) {
if (!disableConstruction) {
if (id) {
var obj = type.get(id);
if (obj)
return obj;
type.register(this, id);
}
else {
type.register(this);
for (var propName in type._properties) {
var prop = type._properties[propName];
if (!prop.get_isStatic() && prop.get_isList()) {
prop.init(this, []);
}
}
}
}
}
var jstype;
if (evalAffectsScope) {
// use eval to generate the type so the function name appears in the debugger
var ctorScript = $format("function {type}(id) { var obj=construct.apply(this, arguments); if(obj) return obj; };" +
"jstype = {type};",
{ type: name });
eval(ctorScript);
}
else {
jstype = construct;
}
this._jstype = window[name] = jstype;
// setup inheritance
this.derivedTypes = [];
var baseJsType;
if (baseType) {
baseJsType = baseType._jstype;
this.baseType = baseType;
baseType.derivedTypes.push(this);
// inherit all shortcut properties that have aleady been defined
for (var propName in baseType._properties)
jstype["$" + propName] = baseType._properties[propName];
}
else {
baseJsType = Entity;
this.baseType = null;
}
disableConstruction = true;
this._jstype.prototype = new baseJsType();
disableConstruction = false;
this._jstype.prototype.constructor = this._jstype;
// formats
var formats = function() { };
formats.prototype = baseJsType.formats;
this._jstype.formats = new formats();
// helpers
jstype.meta = this;
with ({ type: this }) {
jstype.get = function(id) { return type.get(id); };
}
// done...
this._jstype.registerClass(name, baseJsType);
}
Type.prototype = {
newId: function Type$newId() {
return "+c" + this._counter++;
},
register: function Type$register(obj, id) {
obj.meta = new ObjectMeta(this, obj);
if (!id) {
id = this.newId();
obj.meta.isNew = true;
}
else
id = id.toLowerCase();
obj.meta.id = id;
Sys.Observer.makeObservable(obj);
for (var t = this; t; t = t.baseType) {
t._pool[id] = obj;
if (t._known)
t._known.add(obj);
}
this._model.notifyObjectRegistered(obj);
},
changeObjectId: function Type$changeObjectId(oldId, newId) {
oldId = oldId.toLowerCase();
newId = newId.toLowerCase();
var obj = this._pool[oldId];
// TODO: throw exceptions?
if (obj) {
for (var t = this; t; t = t.baseType) {
t._pool[newId] = obj;
delete t._pool[oldId];
t._legacyPool[oldId] = obj;
}
}
obj.meta.id = newId;
},
unregister: function Type$unregister(obj) {
this._model.notifyObjectUnregistered(obj);
for (var t = this; t; t = t.baseType) {
delete t._pool[obj.meta.id];
if (t._known)
t._known.remove(obj);
}
delete obj.meta._obj;
delete obj.meta;
},
get: function Type$get(id) {
id = id.toLowerCase();
return this._pool[id] || this._legacyPool[id];
},
// Gets an array of all objects of this type that have been registered.
// The returned array is observable and collection changed events will be raised
// when new objects are registered or unregistered.
// The array is in no particular order so if you need to sort it, make a copy or use $transform.
known: function Type$known() {
var list = this._known;
if (!list) {
list = this._known = [];
for (id in this._pool)
list.push(this._pool[id]);
Sys.Observer.makeObservable(list);
}
return list;
},
addProperty: function Type$addProperty(def) {
var format = def.format;
if (format && format.constructor === String) {
format = def.type.formats[format];
if (!format)
throwAndLog("model", "Cannot create property {0}.{1} because there is not a '{2}' format defined for {3}", [this._fullName, def.name, def.format, def.type]);
}
var prop = new Property(this, def.name, def.type, def.isList, def.label, format, def.isStatic);
this._properties[def.name] = prop;
// modify jstype to include functionality based on the type definition
function genPropertyShortcut(mtype) {
mtype._jstype["$" + def.name] = prop;
mtype.derivedTypes.forEach(function(t) {
genPropertyShortcut(t);
});
}
genPropertyShortcut(this);
// add members to all instances of this type
//this._jstype.prototype["$" + propName] = prop; // is this useful?
this._jstype.prototype["get_" + def.name] = this._makeGetter(prop, prop.getter);
if (!prop.get_isList())
this._jstype.prototype["set_" + def.name] = this._makeSetter(prop, prop.setter, true);
return prop;
},
_makeGetter: function(receiver, fn) {
return function() {
return fn.call(receiver, this);
}
},
_makeSetter: function(receiver, fn, notifiesChanges) {
var setter = function(val) {
fn.call(receiver, this, val);
};
setter.__notifies = !!notifiesChanges;
return setter;
},
get_model: function() {
return this._model;
},
get_fullName: function() {
return this._fullName;
},
get_jstype: function() {
return this._jstype;
},
property: function(name, thisOnly) {
if (!thisOnly)
return new PropertyChain(this, name);
var prop;
for (var t = this; t && !prop; t = t.baseType) {
prop = t._properties[name];
if (prop)
return prop;
}
return null;
},
addRule: function Type$addRule(rule) {
function Type$addRule$init(obj, prop) {
Type$addRule$fn(obj, prop, rule.init ? rule.init : rule.execute);
}
function Type$addRule$execute(obj, prop) {
Type$addRule$fn(obj, prop, rule.execute);
}
function Type$addRule$fn(obj, prop, fn) {
if (rule._isExecuting)
return;
try {
prop.get_containingType().get_model().beginValidation();
rule._isExecuting = true;
log("rule", "executing rule '{0}' that depends on property '{1}'", [rule, prop]);
fn.call(rule, obj);
}
catch (err) {
throwAndLog("rules", "Error running rule '{0}': {1}", [rule, err]);
}
finally {
rule._isExecuting = false;
prop.get_containingType().get_model().endValidation();
}
}
for (var i = 0; i < rule.inputs.length; ++i) {
var input = rule.inputs[i];
var prop = input.property;
if (input.get_dependsOnChange())
prop.addChanged(Type$addRule$execute);
if (input.get_dependsOnInit())
prop.addInited(Type$addRule$init);
(prop instanceof PropertyChain ? prop.lastProperty() : prop)._addRule(rule);
}
},
// Executes all rules that have a particular property as input
executeRules: function Type$executeRules(obj, prop, start) {
var processing;
if (start === undefined)
this._model.beginValidation();
try {
var i = (start ? start : 0);
var rules = prop.get_rules();
if (rules) {
while (processing = (i < rules.length)) {
var rule = rules[i];
if (!rule._isExecuting) {
rule._isExecuting = true;
if (rule.isAsync) {
// run rule asynchronously, and then pickup running next rules afterwards
var _this = this;
log("rule", "executing rule '{0}' that depends on property '{1}'", [rule, prop]);
rule.execute(obj, function(obj) {
rule._isExecuting = false;
_this.executeRules(obj, prop, i + 1);
});
break;
}
else {
try {
log("rule", "executing rule '{0}' that depends on property '{1}'", [rule, prop]);
rule.execute(obj);
}
finally {
rule._isExecuting = false;
}
}
}
++i;
}
}
}
finally {
if (!processing)
this._model.endValidation();
}
},
set_originForNewProperties: function(value) {
this._originForNewProperties = value;
},
get_originForNewProperties: function() {
return this._originForNewProperties;
},
set_origin: function(value) {
this._origin = value;
},
get_origin: function() {
return this._origin;
}
}
Type.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.Type = Type;
Type.registerClass("ExoWeb.Model.Type");
//////////////////////////////////////////////////////////////////////////////////////
/// <remarks>
/// If the interface for this class is changed it should also be changed in
/// PropertyChain, since PropertyChain acts as an aggregation of properties
/// that can be treated as a single property.
/// </remarks>
///////////////////////////////////////////////////////////////////////////////
function Property(containingType, name, jstype, isList, label, format, isStatic) {
this._containingType = containingType;
this._name = name;
this._jstype = jstype;
this._label = label || name.replace(/([^A-Z]+)([A-Z])/g, "$1 $2");
this._format = format;
this._isList = !!isList;
this._isStatic = !!isStatic;
if (containingType.get_originForNewProperties())
this._origin = containingType.get_originForNewProperties();
}
Property.mixin({
rule: function Property$rule(type) {
if (this._rules) {
for (var i = 0; i < this._rules.length; i++) {
var rule = this._rules[i];
if (rule instanceof type)
return rule;
}
}
return null;
},
_addRule: function Property$_addRule(type) {
if (!this._rules)
this._rules = [type];
else
this._rules.push(type);
},
get_rules: function Property$get_rules() {
return this._rules;
},
toString: function() {
return this.get_label();
},
get_containingType: function() {
return this._containingType;
},
get_jstype: function() {
return this._jstype;
},
get_format: function() {
return this._format;
},
get_origin: function() {
return this._origin ? this._origin : this._containingType.get_origin();
},
getter: function(obj) {
return obj[this._name];
},
setter: function(obj, val) {
if (!this.canSetValue(obj, val))
throwAndLog(["model", "entity"], "Cannot set {0}={1}. A value of type {2} was expected", [this._name, val === undefined ? "<undefined>" : val, this._jstype.getName()]);
var old = obj[this._name];
if (old !== val) {
obj[this._name] = val;
// NOTE: property change should be broadcast before rules are run so that if
// any rule causes a roundtrip to the server these changes will be available
this._containingType.get_model().notifyAfterPropertySet(obj, this, val, old);
this._raiseEvent("changed", [obj, this]);
Sys.Observer.raisePropertyChanged(obj, this._name);
}
},
get_isEntityType: function() {
return this.get_jstype().meta && !this._isList;
},
get_isEntityListType: function() {
return this.get_jstype().meta && this._isList;
},
get_isValueType: function() {
return !this.get_jstype().meta;
},
get_isList: function() {
return this._isList;
},
get_isStatic: function() {
return this._isStatic;
},
get_label: function() {
return this._label;
},
get_name: function() {
return this._name;
},
get_path: function() {
return this._isStatic ? (this._containingType.get_fullName() + "." + this._name) : this._name;
},
canSetValue: function Property$canSetValue(obj, val) {
// only allow values of the correct data type to be set in the model
if (val === null || val === undefined)
return true;
if (val.constructor) {
// for entities check base types as well
if (val.constructor.meta) {
for (var valType = val.constructor.meta; valType; valType = valType.baseType)
if (valType._jstype === this._jstype)
return true;
return false;
}
else {
return val.constructor === this._jstype
}
}
else {
var valType;
switch (typeof (val)) {
case "string": valType = String; break;
case "number": valType = Number; break;
case "boolean": valType = Boolean; break;
}
return valType === this._jstype;
};
},
value: function Property$value(obj, val) {
if (arguments.length == 2) {
var setter = obj["set_" + this._name];
// If a generated setter is found then use it instead of observer, since it will emulate observer
// behavior in order to allow application code to call it directly rather than going through the
// observer. Calling the setter in place of observer eliminates unwanted duplicate events.
if (setter && setter.__notifies)
setter.call(obj, val);
else
Sys.Observer.setValue(obj, this._name, val);
}
else {
var target = (this._isStatic ? this._containingType.get_jstype() : obj);
if (target == undefined)
ExoWeb.trace.throwAndLog(["model"],
"Cannot get value for {0}static property \"{1}\" on type \"{2}\": target is undefined.",
[(this._isStatic ? "" : "non-"), this.get_path(), this._containingType.get_fullName()]);
// access directly since the caller might make a distinction between null and undefined
return target[this._name];
}
},
init: function Property$init(obj, val, force) {
var target = (this._isStatic ? this._containingType.get_jstype() : obj);
var curVal = target[this._name];
if (curVal !== undefined && !(force === undefined || force))
return;
target[this._name] = val;
if (val instanceof Array) {
var prop = this;
Sys.Observer.makeObservable(val);
Sys.Observer.addCollectionChanged(val, function(sender, args) {
prop._raiseEvent("changed", [target, prop]);
prop._containingType.get_model().notifyListChanged(target, prop, args.get_changes());
});
}
this._raiseEvent("inited", [target, this]);
},
isInited: function Property$isInited(obj) {
var target = (this._isStatic ? this._containingType.get_jstype() : obj);
var curVal = target[this._name];
return curVal !== undefined;
},
// starts listening for when property.init() is called. Use obj argument to
// optionally filter the events to a specific object
addInited: function Property$addInited(handler, obj) {
var f;
if (obj)
f = function(target, property) {
if (obj === target)
handler(target, property);
}
else
f = handler;
this._addEvent("inited", f);
},
// starts listening for change events on the property. Use obj argument to
// optionally filter the events to a specific object
addChanged: function Property$addChanged(handler, obj) {
var f;
if (obj)
f = function(target, property) {
if (obj === target)
handler(target, property);
}
else
f = handler;
this._addEvent("changed", f);
},
// Adds a rule to the property that will update its value
// based on a calculation.
calculated: function Property$calculated(options) {
var prop = this;
var rootType;
if (options.rootType)
rootType = options.rootType.meta;
else
rootType = prop._containingType;
var inputs;
if (options.basedOn) {
inputs = options.basedOn.map(function(p) {
if (p instanceof Property)
return new RuleInput(p);
var input;
var parts = p.split(" of ");
if (parts.length >= 2) {
input = new RuleInput(Model.property(parts[1], rootType));
var events = parts[0].split(",");
input.set_dependsOnInit(events.indexOf("init") >= 0);
input.set_dependsOnChange(events.indexOf("change") >= 0);
}
else {
input = new RuleInput(Model.property(parts[0], rootType));
input.set_dependsOnInit(true);
}
if (!input.property)
throwAndLog("model", "Calculated property {0}.{1} is based on an invalid property: {2}", [rootType.get_fullName(), prop._name, p]);
return input;
});
}
else {
inputs = Rule.inferInputs(rootType, options.fn);
inputs.forEach(function(input) {
input.set_dependsOnInit(true);
});
}
var rule = {
init: function Property$calculated$init(obj, property) {
if (!prop.isInited(obj) && inputs.every(function(input) { return input.property.isInited(obj); })) {
// init the calculated property
prop.init(obj, options.fn.apply(obj));
}
},
execute: function Property$calculated$recalc(obj) {
if (prop._isList) {
calc = function Property$calculated$calcList(obj) {
// re-calculate the list values
var newList = options.fn.apply(obj);
LazyLoader.load(newList, null, function() {
// compare the new list to the old one to see if changes were made
var curList = prop.value(obj);
if (!curList) {
curList = [];
prop.init(obj, curList);
}
if (newList.length === curList.length) {
var noChanges = true;
for (var i = 0; i < newList.length; ++i) {
if (newList[i] !== curList[i]) {
noChanges = false;
break;
}
}
if (noChanges)
return;
}
// update the current list so observers will receive the change events
curList.beginUpdate();
curList.clear();
curList.addRange(newList);
curList.endUpdate();
});
}
}
else {
var newValue = options.fn.apply(obj);
if (newValue !== prop.value(obj))
Sys.Observer.setValue(obj, prop._name, newValue);
}
},
toString: function() { return "calculation of " + prop._name; }
};
Rule.register(rule, inputs);
// go ahead and calculate this property for all known objects
//Array.forEach(this._containingType.known(), calc);
return this;
}
});
Property.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.Property = Property;
Property.registerClass("ExoWeb.Model.Property");
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Encapsulates the logic required to work with a chain of properties and
/// a root object, allowing interaction with the chain as if it were a
/// single property of the root object.
/// </summary>
///////////////////////////////////////////////////////////////////////////
function PropertyChain(rootType, path) {
var type = rootType;
var chain = this;
this._properties = [];
this._filters = [];
(path instanceof Array ? path : path.split(".")).forEach(function(step) {
var parsed = parsePropertyStep(step);
if (!parsed)
throwAndLog("model", "Syntax error in property path: {0}", [path]);
var prop = type.property(parsed.property, true);
if (!prop)
throwAndLog("model", "Path '{0}' references an unknown property: {1}.{2}", [path, type.get_fullName(), parsed.property]);
chain._properties.push(prop);
if (parsed.cast) {
type = type.get_model().type(parsed.cast);
if (!type)
throwAndLog("model", "Path '{0}' references an unknown type: {1}", [path, parsed.cast]);
with ({type: type.get_jstype() }) {
chain._filters[chain._properties.length - 1] = function(target) {
return target instanceof type;
};
}
}
else
type = prop.get_jstype().meta;
});
if (this._properties.length == 0)
throwAndLog(["model"], "PropertyChain cannot be zero-length.");
}
function parsePropertyStep(step) {
var parsed = step.match(/^([a-z0-9_]+)(<([a-z0-9_]+)>)?$/i);
if (!parsed)
return null;
var result = { property: parsed[1] };
if (parsed[3])
result.cast = parsed[3];
return result;
}
PropertyChain.prototype = {
all: function() {
return this._properties;
},
append: function(prop) {
Array.addRange(this._properties, prop.all());
},
// Iterates over all objects along a property chain starting with the root object (obj).
// An optional propFilter can be specified to only iterate over objects on one property
// within the chain.
each: function(obj, callback, propFilter /*, target, p*/) {
if (!callback || typeof (callback) != "function")
throwAndLog(["model"], "Invalid Parameter: callback function");
if (!obj)
throwAndLog(["model"], "Invalid Parameter: source object");
var target = arguments[3] || obj;
var lastProp = null;
for (var p = arguments[4] || 0; p < this._properties.length && (!propFilter || lastProp !== propFilter); p++) {
var prop = this._properties[p];
var enableCallback = (!propFilter || prop === propFilter);
if (target instanceof Array) {
for (var i = 0; i < target.length; ++i) {
if (enableCallback && (!this._filters[p] || this._filters[p](target))) {
if (callback(target[i], prop) === false)
return false;
}
if (this.each(obj, callback, propFilter, prop.value(target[i]), p + 1) === false)
return false;
}
}
else if (enableCallback && (!this._filters[p] || this._filters[p](target))) {
if (callback(target, prop) === false)
return false;
}
target = prop.value(target);
lastProp = prop;
}
return true;
},
get_path: function PropertyChain$get_path() {
if (!this._path) {
var parts = [];
if (this._properties[0].get_isStatic())
parts.push(this._properties[0].get_containingType().get_fullName());
this._properties.forEach(function(p) { parts.push(p.get_name()); })
this._path = parts.join(".");
}
return this._path;
},
firstProperty: function() {
return this._properties[0];
},
lastProperty: function() {
return this._properties[this._properties.length - 1];
},
lastTarget: function(obj) {
for (var p = 0; p < this._properties.length - 1; p++) {
var prop = this._properties[p];
obj = prop.value(obj);
}
return obj;
},
prepend: function(prop) {
var newProps = prop.all();
for (var p = newProps.length - 1; p >= 0; p--) {
Array.insert(this._properties, 0, newProps[p]);
}
},
canSetValue: function PropertyChain$canSetValue(obj, value) {
return this.lastProperty().canSetValue(this.lastTarget(obj), value);
},
// Determines if this property chain connects two objects.
// viaProperty is optional but will speed up the search.
connects: function PropertyChain$connects(fromRoot, toObj, viaProperty) {
var connected = false;
this.each(fromRoot, function(target) {
if (target === toObj) {
connected = true;
return false;
}
}, viaProperty);
return connected;
},
// Listens for when property.init() is called on all properties in the chain. Use obj argument to
// optionally filter the events to a specific object
addInited: function PropertyChain$addInited(handler, obj) {
var chain = this;
if (this._properties.length == 1) {
// OPTIMIZATION: no need to search all known objects for single property chains
this._properties[0].addInited(function PropertyChain$_raiseInited$1Prop(sender, property) {
handler(sender, chain);
}, obj);
}
else {
for (var p = 0; p < this._properties.length; p++) {
with ({ priorProp: p == 0 ? undefined : this._properties[p - 1] }) {
if (obj) {
// CASE: using object filter
this._properties[p].addInited(function PropertyChain$_raiseInited$1Obj(sender, property) {
if (chain.isInited(obj))
handler(obj, chain);
}, obj);
}
else {
// CASE: no object filter
this._properties[p].addInited(function PropertyChain$_raiseInited$Multi(sender, property) {
// scan all known objects of this type and raise event for any instance connected
// to the one that sent the event.
Array.forEach(chain.firstProperty().get_containingType().known(), function(known) {
if (chain.connects(known, sender, priorProp) && chain.isInited(known))
handler(known, chain);
});
});
}
}
}
}
},
// starts listening for change events along the property chain on any known instances. Use obj argument to
// optionally filter the events to a specific object
addChanged: function PropertyChain$addChanged(handler, obj) {
var chain = this;
if (this._properties.length == 1) {
// OPTIMIZATION: no need to search all known objects for single property chains
this._properties[0].addChanged(function PropertyChain$_raiseChanged$1Prop(sender, property) {
handler(sender, chain);
}, obj);
}
else {
for (var p = 0; p < this._properties.length; p++) {
with ({ priorProp: p == 0 ? undefined : this._properties[p - 1] }) {
if (obj) {
// CASE: using object filter
this._properties[p].addChanged(function PropertyChain$_raiseChanged$1Obj(sender, property) {
if (chain.connects(obj, sender, priorProp))
handler(obj, chain);
});
}
else {
// CASE: no object filter
this._properties[p].addChanged(function PropertyChain$_raiseChanged$Multi(sender, property) {
// scan all known objects of this type and raise event for any instance connected
// to the one that sent the event.
Array.forEach(chain.firstProperty().get_containingType().known(), function(known) {
if (chain.connects(known, sender, priorProp))
handler(known, chain);
});
});
}
}
}
}
},
// Property pass-through methods
///////////////////////////////////////////////////////////////////////
get_containingType: function PropertyChain$get_containingType() {
return this.firstProperty().get_containingType();
},
get_jstype: function PropertyChain$get_jstype() {
return this.lastProperty().get_jstype();
},
get_format: function PropertyChain$get_format() {
return this.lastProperty().get_format();
},
get_isList: function PropertyChain$get_isList() {
return this.lastProperty().get_isList();
},
get_isStatic: function PropertyChain$get_isStatic() {
// TODO
return this.lastProperty().get_isStatic();
},
get_label: function PropertyChain$get_label() {
return this.lastProperty().get_label();
},
get_name: function PropertyChain$get_name() {
return this.lastProperty().get_name();
},
get_isValueType: function PropertyChain$get_isValueType() {
return this.lastProperty().get_isValueType();
},
get_isEntityType: function PropertyChain$get_isEntityType() {
return this.lastProperty().get_isEntityType();
},
get_isEntityListType: function PropertyChain$get_isEntityListType() {
return this.lastProperty().get_isEntityListType();
},
get_rules: function PropertyChain$_get_rules() {
return this.lastProperty().get_rules();
},
value: function PropertyChain$value(obj, val) {
var target = this.lastTarget(obj);
var prop = this.lastProperty();
if (arguments.length == 2)
prop.value(target, val);
else
return prop.value(target);
},
isInited: function PropertyChain$isInited(obj) {
var allInited = true;
this.each(obj, function(target, property) {
if (!property.isInited(target)) {
allInited = false;
return false;
}
});
return allInited;
},
toString: function() {
return this.get_label();
}
},
ExoWeb.Model.PropertyChain = PropertyChain;
PropertyChain.registerClass("ExoWeb.Model.PropertyChain");
///////////////////////////////////////////////////////////////////////////
function ObjectMeta(type, obj) {
this._obj = obj;
this.type = type;
this._issues = [];
this._propertyIssues = {};
}
ObjectMeta.prototype = {
executeRules: function ObjectMeta$executeRules(prop) {
this.type.get_model()._validatedQueue.push({ sender: this, property: prop.get_name() });
this._raisePropertyValidating(prop.get_name());
this.type.executeRules(this._obj, prop);
},
property: function ObjectMeta$property(propName) {
return this.type.property(propName);
},
clearIssues: function ObjectMeta$clearIssues(origin) {
var issues = this._issues;
for (var i = issues.length - 1; i >= 0; --i) {
var issue = issues[i];
if (issue.get_origin() == origin) {
this._removeIssue(i);
this._raisePropertiesValidated(issue.get_properties());
}
}
},
issueIf: function ObjectMeta$issueIf(issue, condition) {
// always remove and re-add the issue to preserve order
var idx = $.inArray(issue, this._issues);
if (idx >= 0)
this._removeIssue(idx);
if (condition)
this._addIssue(issue);
if ((idx < 0 && condition) || (idx >= 0 && !condition))
this._raisePropertiesValidated(issue.get_properties());
},
_addIssue: function(issue) {
this._issues.push(issue);
// update _propertyIssues
var props = issue.get_properties();
for (var i = 0; i < props.length; ++i) {
var propName = props[i].get_name();
var pi = this._propertyIssues[propName];
if (!pi) {
pi = [];
this._propertyIssues[propName] = pi;
}
pi.push(issue);
}
},
_removeIssue: function(idx) {
var issue = this._issues[idx];
this._issues.splice(idx, 1);
// update _propertyIssues
var props = issue.get_properties();
for (var i = 0; i < props.length; ++i) {
var propName = props[i].get_name();
var pi = this._propertyIssues[propName];
var piIdx = $.inArray(issue, pi);
pi.splice(piIdx, 1);
}
},
issues: function ObjectMeta$issues(prop) {
if (!prop)
return this._issues;
var ret = [];
for (var i = 0; i < this._issues.length; ++i) {
var issue = this._issues[i];
var props = issue.get_properties();
for (var p = 0; p < props.length; ++p) {
if (props[p] == prop) {
ret.push(issue);
break;
}
}
}
return ret;
},
_raisePropertiesValidated: function(properties) {
var queue = this.type.get_model()._validatedQueue;
for (var i = 0; i < properties.length; ++i)
queue.push({ sender: this, property: properties[i].get_name() });
},
addPropertyValidated: function(propName, handler) {
this._addEvent("propertyValidated:" + propName, handler);
},
_raisePropertyValidating: function(propName) {
var queue = this.type.get_model()._validatingQueue;
queue.push({ sender: this, propName: propName });
},
addPropertyValidating: function(propName, handler) {
this._addEvent("propertyValidating:" + propName, handler);
},
destroy: function() {
this.type.unregister(this.obj);
}
}
ObjectMeta.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.ObjectMeta = ObjectMeta;
ObjectMeta.registerClass("ExoWeb.Model.ObjectMeta");
//////////////////////////////////////////////////////////////////////////////////////
function Rule() { }
Rule.register = function Rule$register(rule, inputs, isAsync) {
rule.isAsync = !!isAsync;
rule.inputs = inputs.map(function(item) {
return item instanceof RuleInput ? item : new RuleInput(item);
});
rule.inputs[0].property.get_containingType().addRule(rule);
}
Rule.inferInputs = function Rule$inferInputs(rootType, func) {
var inputs = [];
var match;
while (match = /this\.([a-zA-Z0-9_.]+)/g.exec(func.toString())) {
inputs.push(new RuleInput(rootType.property(match[1]).lastProperty()));
}
return inputs;
}
ExoWeb.Model.Rule = Rule;
Rule.registerClass("ExoWeb.Model.Rule");
//////////////////////////////////////////////////////////////////////////////////////
function RuleInput(property) {
this.property = property;
}
RuleInput.prototype = {
set_dependsOnInit: function RuleInput$set_dependsOnInit(value) {
this._init = value;
},
get_dependsOnInit: function RuleInput$get_dependsOnInit() {
return this._init === undefined ? false : this._init;
},
set_dependsOnChange: function RuleInput$set_dependsOnChange(value) {
this._change = value;
},
get_dependsOnChange: function RuleInput$get_dependsOnChange() {
return this._change === undefined ? true : this._change;
}
};
ExoWeb.Model.RuleInput = RuleInput;
RuleInput.registerClass("ExoWeb.Model.RuleInput");
//////////////////////////////////////////////////////////////////////////////////////
function RequiredRule(options, properties) {
this.prop = properties[0];
this.err = new RuleIssue(this.prop.get_label() + " is required", properties, this);
Rule.register(this, properties);
}
RequiredRule.prototype = {
execute: function(obj) {
var val = this.prop.value(obj);
if (val instanceof Array) {
obj.meta.issueIf(this.err, val.length == 0);
}
else {
obj.meta.issueIf(this.err, val == null || ($.trim(val.toString()) == ""));
}
},
toString: function() {
return $format("{0}.{1} is required", [this.prop.get_containingType().get_fullName(), this.prop.get_name()]);
}
}
Rule.required = RequiredRule;
//////////////////////////////////////////////////////////////////////////////////////
function RangeRule(options, properties) {
this.prop = properties[0];
this.min = options.min;
this.max = options.max;
var hasMin = (this.min !== undefined && this.min != null);
var hasMax = (this.max !== undefined && this.max != null);
if (hasMin && hasMax) {
this.err = new RuleIssue($format("{prop} must be between {min} and {max}", this), properties, this);
this._test = this._testMinMax;
}
else if (hasMin) {
this.err = new RuleIssue($format("{prop} must be at least {min}", this), properties, this);
this._test = this._testMin;
}
else if (hasMax) {
this.err = new RuleIssue($format("{prop} must no more than {max}", this), properties, this);
this._test = this._testMax;
}
Rule.register(this, properties);
}
RangeRule.prototype = {
execute: function(obj) {
var val = this.prop.value(obj);
obj.meta.issueIf(this.err, this._test(val));
},
_testMinMax: function(val) {
return val < this.min || val > this.max;
},
_testMin: function(val) {
return val < this.min;
},
_testMax: function(val) {
return val > this.max;
},
toString: function() {
return $format("{0}.{1} in range, min: {2}, max: {3}", [this.prop.get_containingType().get_fullName(), this.prop.get_name(), this.min, this.max]);
}
}
Rule.range = RangeRule;
//////////////////////////////////////////////////////////////////////////////////////
function AllowedValuesRule(options, properties) {
var prop = this.prop = properties[0];
this.path = options.source;
this.err = new RuleIssue($format("{prop} has an invalid value", this), properties, this);
Rule.register(this, properties);
this._needsInit = true;
}
AllowedValuesRule.prototype = {
_init: function() {
if (this._needsInit) {
// type is undefined or not loaded
if (LazyLoader.isLoaded(this.prop.get_containingType()))
this._propertyChain = ExoWeb.Model.Model.property(this.path, this.prop.get_containingType());
delete this._needsInit;
}
},
execute: function(obj) {
this._init();
// get the list of allowed values of the property for the given object
var allowed = this.values(obj);
// ignore if allowed values list is undefined (non-existent or unloaded type) or has not been loaded
if (allowed !== undefined && LazyLoader.isLoaded(allowed)) {
// get the current value of the property for the given object
var val = this.prop.value(obj);
// ensure that the value or list of values is in the allowed values list (single and multi-select)
if (val instanceof Array)
obj.meta.issueIf(this.err, !val.every(function(item) { return Array.contains(allowed, item); }));
else
obj.meta.issueIf(this.err, val && !Array.contains(allowed, val));
}
},
propertyChain: function(obj) {
this._init();
return this._propertyChain;
},
values: function(obj) {
this._init();
if (this._propertyChain) {
// get the allowed values from the property chain
return this._propertyChain.value(obj);
}
},
toString: function() {
return $format("{0}.{1} allowed values", [this.prop.get_containingType().get_fullName(), this.prop.get_name()]);
}
}
Rule.allowedValues = AllowedValuesRule;
Property.mixin({
allowedValues: function(options) {
// create a rule that will recalculate allowed values when dependencies change
var source = this.get_name() + "AllowedValues";
var valuesProp = this.get_containingType().addProperty(source, this.get_jstype(), true);
valuesProp.calculated(options);
new AllowedValuesRule({ source: source }, [this]);
}
});
///////////////////////////////////////////////////////////////////////////////////////
function StringLengthRule(options, properties) {
this.prop = properties[0];
this.min = options.min;
this.max = options.max;
var hasMin = (this.min !== undefined && this.min != null);
var hasMax = (this.max !== undefined && this.max != null);
if (hasMin && hasMax) {
this.err = new RuleIssue($format("{prop} must be between {min} and {max} characters", this), properties, this);
this._test = this._testMinMax;
}
else if (hasMin) {
this.err = new RuleIssue($format("{prop} must be at least {min} characters", this), properties, this);
this._test = this._testMin;
}
else if (hasMax) {
this.err = new RuleIssue($format("{prop} must be no more than {max} characters", this), properties, this);
this._test = this._testMax;
}
Rule.register(this, properties);
}
StringLengthRule.prototype = {
execute: function(obj) {
var val = this.prop.value(obj);
obj.meta.issueIf(this.err, this._test(val || ""));
},
_testMinMax: function(val) {
return val.length < this.min || val.length > this.max;
},
_testMin: function(val) {
return val.length < this.min;
},
_testMax: function(val) {
return val.length > this.max;
},
toString: function() {
return $format("{0}.{1} in range, min: {2}, max: {3}", [this.prop.get_containingType().get_fullName(), this.prop.get_name(), this.min, this.max]);
}
}
Rule.stringLength = StringLengthRule;
//////////////////////////////////////////////////////////////////////////////////////
function EventQueue(raise, areEqual) {
this._queueing = 0;
this._queue = [];
this._raise = raise;
this._areEqual = areEqual;
}
EventQueue.prototype = {
startQueueing: function EventQueue$startQueueing() {
++this._queueing;
},
stopQueueing: function EventQueue$stopQueueing() {
if (--this._queueing === 0)
this.raiseQueue();
},
push: function EventQueue$push(item) {
if (this._queueing) {
if (this._areEqual) {
for (var i = 0; i < this._queue.length; ++i) {
if (this._areEqual(item, this._queue[i]))
return;
}
}
this._queue.push(item);
}
else
this._raise(item);
},
raiseQueue: function EventQueue$raiseQueue() {
try {
for (var i = 0; i < this._queue.length; ++i)
this._raise(this._queue[i]);
}
finally {
if (this._queue.length > 0)
this._queue = [];
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
function RuleIssue(message, relatedProperties, origin) {
this._properties = relatedProperties || [];
this._message = message;
this._origin = origin;
}
RuleIssue.prototype = {
get_properties: function() {
return this._properties;
},
get_message: function() {
return this._message;
},
get_origin: function() {
return this._origin;
},
set_origin: function(origin) {
this._origin = origin;
},
equals: function(o) {
return o.property.equals(this.property) && o._message.equals(this._message);
}
}
ExoWeb.Model.RuleIssue = RuleIssue;
RuleIssue.registerClass("ExoWeb.Model.RuleIssue");
//////////////////////////////////////////////////////////////////////////////////////
function FormatIssue(message, invalidValue) {
this._message = message;
this._invalidValue = invalidValue;
}
FormatIssue.prototype = {
get_message: function() {
return this._message;
},
toString: function() {
return this._invalidValue;
},
get_invalidValue: function() {
return this._invalidValue;
}
}
ExoWeb.Model.FormatIssue = FormatIssue;
FormatIssue.registerClass("ExoWeb.Model.FormatIssue");
//////////////////////////////////////////////////////////////////////////////////////
function Format(options) {
this._convert = options.convert;
this._convertBack = options.convertBack;
this._description = options.description;
this._nullString = options.nullString || "";
this._undefinedString = options.undefinedString || "";
}
Format.fromTemplate = (function Format$fromTemplate(convertTemplate) {
return new Format({
convert: function convert(obj) {
if (obj === null || obj === undefined)
return "";
return $format(convertTemplate, obj);
}
});
}).cached({ key: function(convertTemplate) { return convertTemplate; } });
Format.mixin({
convert: function(val) {
if (val === undefined)
return this._undefinedString;
if (val == null)
return this._nullString;
if (val instanceof FormatIssue)
return val.get_invalidValue();
if (!this._convert)
return val;
return this._convert(val);
},
convertBack: function(val) {
if (val == this._nullString)
return null;
if (val == this._undefinedString)
return;
if (val.constructor == String) {
val = val.trim();
if (val.length == 0)
return null;
}
if (!this._convertBack)
return val;
try {
return this._convertBack(val);
}
catch (err) {
return new FormatIssue(this._description ?
"{value} must be formatted as " + this._description :
"{value} is not properly formatted",
val);
}
}
});
ExoWeb.Model.Format = Format;
Format.registerClass("ExoWeb.Model.Format");
// Type Format Strings
/////////////////////////////////////////////////////////////////////////////////////////////////////////
Number.formats = {};
String.formats = {};
Date.formats = {};
TimeSpan.formats = {};
Boolean.formats = {};
//TODO: number formatting include commas
Number.formats.Integer = new Format({
description: "#,###",
convert: function(val) {
return Math.round(val).toString();
},
convertBack: function(str) {
if (!/^([-\+])?(\d+)?\,?(\d+)?\,?(\d+)?\,?(\d+)$/.test(str))
throw "invalid format";
return parseInt(str, 10);
}
});
Number.formats.Float = new Format({
description: "#,###.#",
convert: function(val) {
return val.toString();
},
convertBack: function(str) {
return parseFloat(str);
}
});
Number.formats.$system = Number.formats.Float;
String.formats.Phone = new Format({
description: "###-###-####",
convertBack: function(str) {
if (!/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/.test(str))
throw "invalid format";
return str;
}
});
String.formats.$system = new Format({
convertBack: function(val) {
return val ? $.trim(val) : val;
}
});
Boolean.formats.YesNo = new Format({
convert: function(val) { return val ? "yes" : "no"; },
convertBack: function(str) { return str == "yes"; }
});
Boolean.formats.TrueFalse = new Format({
convert: function(val) { return val ? "true" : "false"; },
convertBack: function(str) { return (str.toLowerCase() == "true"); }
});
Boolean.formats.$system = Boolean.formats.TrueFalse;
Boolean.formats.$display = Boolean.formats.YesNo;
Date.formats.DateTime = new Format({
description: "mm/dd/yyyy hh:mm AM/PM",
convert: function(val) {
return val.format("MM/dd/yyyy h:mm tt");
},
convertBack: function(str) {
var val = Date.parseInvariant(str);
if (val != null)
return val;
throw "invalid date";
}
});
Date.formats.ShortDate = new Format({
description: "mm/dd/yyyy",
convert: function(val) {
return val.format("M/d/yyyy");
},
convertBack: function(str) {
var val = Date.parseInvariant(str);
if (val != null)
return val;
throw "invalid date";
}
});
Date.formats.Time = new Format({
description: "HH:MM AM/PM",
convert: function(val) {
return val.format("h:mm tt");
},
convertBack: function(str) {
var parser = /^(1[0-2]|0?[1-9]):([0-5][0-9]) *(AM?|(PM?))$/i;
var parts = str.match(parser);
if (!parts)
throw "invalid time";
// build new date, start with current data and overwite the time component
var val = new Date();
// hours
if (parts[4])
val.setHours(parseInt(parts[1], 10) + 12); // PM
else
val.setHours(parseInt(parts[1], 10)); // AM
// minutes
val.setMinutes(parseInt(parts[2], 10));
// keep the rest of the time component clean
val.setSeconds(0);
val.setMilliseconds(0);
return val;
}
});
Date.formats.$system = Date.formats.DateTime;
Date.formats.$display = Date.formats.DateTime;
TimeSpan.formats.Meeting = new ExoWeb.Model.Format({
convert: function(val) {
var num;
var label;
if (val.totalHours < 1) {
num = Math.round(val.totalMinutes);
label = "minute";
}
else if (val.totalDays < 1) {
num = Math.round(val.totalHours * 100) / 100;
label = "hour";
}
else {
num = Math.round(val.totalDays * 100) / 100;
label = "day";
}
return num == 1 ? (num + " " + label) : (num + " " + label + "s");
},
convertBack: function(str) {
var parser = /^([0-9]+(\.[0-9]+)?) *(m((inute)?s)?|h((our)?s?)|hr|d((ay)?s)?)$/i;
var parts = str.match(parser);
if (!parts)
throw "invalid format";
var num = parseFloat(parts[1]);
var ms;
if (parts[3].startsWith("m"))
ms = num * 60 * 1000;
else if (parts[3].startsWith("h"))
ms = num * 60 * 60 * 1000;
else if (parts[3].startsWith("d"))
ms = num * 24 * 60 * 60 * 1000;
return new TimeSpan(ms);
}
});
TimeSpan.formats.$display = TimeSpan.formats.Meeting;
TimeSpan.formats.$system = TimeSpan.formats.Meeting; // TODO: implement Exact format
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function LazyLoader() {
}
LazyLoader.eval = function LazyLoader$eval(target, path, successCallback, errorCallback, scopeChain) {
if (!path)
path = [];
else if (!(path instanceof Array))
path = path.split(".");
scopeChain = scopeChain || [window];
target = target || Array.dequeue(scopeChain);
while (path.length > 0) {
var prop = Array.dequeue(path);
if (!LazyLoader.isLoaded(target, prop)) {
LazyLoader.load(target, prop, function() {
var nextTarget = ExoWeb.getValue(target, prop);
if (nextTarget === undefined) {
if (scopeChain.length > 0) {
Array.insert(path, 0, prop);
LazyLoader.eval(Array.dequeue(scopeChain), path, successCallback, errorCallback, scopeChain);
}
else if (errorCallback)
errorCallback("Property is undefined: " + prop);
else
throwAndLog(["lazyLoad"], "Cannot complete property evaluation because a property is undefined: {0}", [prop]);
}
else if (nextTarget != null)
LazyLoader.eval(nextTarget, path, successCallback, errorCallback, []);
else if (successCallback)
successCallback(null);
});
return;
}
else {
var propValue = ExoWeb.getValue(target, prop);
if (propValue === undefined) {
if (scopeChain.length > 0) {
Array.insert(path, 0, prop);
target = Array.dequeue(scopeChain);
}
else {
if (errorCallback)
errorCallback("Property is undefined: " + prop)
else
throwAndLog(["lazyLoad"], "Cannot complete property evaluation because a property is undefined: {0}", [prop]);
return;
}
}
else if (propValue == null) {
if (successCallback)
successCallback(null);
return;
}
else {
if (scopeChain.length > 0)
scopeChain = [];
target = propValue;
}
}
}
// Load final object
if (target != null && !LazyLoader.isLoaded(target))
LazyLoader.load(target, null, function() { successCallback(target); });
else if (successCallback)
successCallback(target);
}
LazyLoader.isLoaded = function LazyLoader$isLoaded(obj, propName) {
if (obj === undefined)
return false;
var reg = obj._lazyLoader;
if (!reg)
return true;
var loader;
if (propName && reg.byProp)
loader = reg.byProp[propName];
if (!loader)
loader = reg.allProps;
return !loader || (loader.isLoaded && obj._lazyLoader.isLoaded(obj, propName));
}
LazyLoader.load = function LazyLoader$load(obj, propName, callback) {
var reg = obj._lazyLoader;
if (!reg) {
if (callback)
callback();
}
else {
var loader;
if (propName && reg.byProp)
loader = reg.byProp[propName];
if (!loader)
loader = reg.allProps;
if (!loader)
throwAndLog(["lazyLoad"], "Attempting to load object but no appropriate loader is registered. object: {0}, property: {1}", [obj, propName]);
loader.load(obj, propName, callback);
}
}
LazyLoader.isRegistered = function LazyLoader$isRegistered(obj, loader, propName) {
var reg = obj._lazyLoader;
if (!reg)
return false;
if (propName)
return reg.byProp && reg.byProp[propName] === loader;
return reg.allProps === loader;
}
LazyLoader.register = function LazyLoader$register(obj, loader, propName) {
var reg = obj._lazyLoader;
if (!reg)
reg = obj._lazyLoader = {};
if (propName) {
if (!reg.byProp)
reg.byProp = {};
reg.byProp[propName] = loader;
}
else
obj._lazyLoader.allProps = loader;
}
LazyLoader.unregister = function LazyLoader$unregister(obj, loader, propName) {
var reg = obj._lazyLoader;
if (!reg)
return;
if (propName) {
delete reg.byProp[propName];
} else if (reg.byProp) {
var allDeleted = true;
for (var p in reg.byProp) {
if (reg.byProp[p] === loader)
delete reg.byProp[p];
else
allDeleted = false;
}
if (allDeleted)
delete reg.byProp;
}
if (reg.allProps === loader)
delete reg.allProps;
if (!reg.byProp && !reg.allProps)
delete obj._lazyLoader;
}
ExoWeb.Model.LazyLoader = LazyLoader;
LazyLoader.registerClass("ExoWeb.Model.LazyLoader");
}
if (Sys && Sys.loader) {
Sys.loader.registerScript("ExoWebModel", null, execute);
}
else {
execute();
}
})();
|
ExoWeb/Client/exoweb.model.js
|
Type.registerNamespace("ExoWeb.Model");
(function() {
function execute() {
var evalAffectsScope = false;
eval("evalAffectsScope = true;");
var undefined;
var log = ExoWeb.trace.log;
var throwAndLog = ExoWeb.trace.throwAndLog;
var disableConstruction = false;
//////////////////////////////////////////////////////////////////////////////////////
function Model() {
this._types = {};
this._validatingQueue = new EventQueue(
function(e) {
var meta = e.sender;
var issues = meta._propertyIssues[e.propName];
meta._raiseEvent("propertyValidating:" + e.propName, [meta, e.propName])
},
function(a, b) {
return a.sender == b.sender && a.propName == b.propName;
}
);
this._validatedQueue = new EventQueue(
function(e) {
var meta = e.sender;
var propName = e.property;
var issues = meta._propertyIssues[propName];
meta._raiseEvent("propertyValidated:" + propName, [meta, issues ? issues : []])
},
function(a, b) {
return a.sender == b.sender && a.property == b.property;
}
);
}
Model.property = function(path, thisType) {
var part = path.split(".");
var isGlobal = part[0] !== "this";
var type;
if (isGlobal) {
// locate first model type
for (var t = window[Array.dequeue(part)]; t && part.length > 0; t = t[Array.dequeue(part)]) {
if (t.meta) {
type = t.meta;
break;
}
}
if (!type)
throwAndLog(["model"], "Invalid property path: {0}", [path]);
}
else {
if (thisType instanceof Function)
type = thisType.meta;
else
type = thisType;
Array.dequeue(part);
}
return type.property(part.join("."));
}
Model.prototype = {
addType: function Model$addType(name, base) {
return this._types[name] = new Type(this, name, base);
},
beginValidation: function Model$beginValidation() {
this._validatingQueue.startQueueing();
this._validatedQueue.startQueueing();
},
endValidation: function Model$endValidation() {
this._validatingQueue.stopQueueing();
this._validatedQueue.stopQueueing();
},
type: function(name) {
return this._types[name];
},
addAfterPropertySet: function(handler) {
this._addEvent("afterPropertySet", handler);
},
notifyAfterPropertySet: function(obj, property, newVal, oldVal) {
this._raiseEvent("afterPropertySet", [obj, property, newVal, oldVal]);
},
addObjectRegistered: function(func) {
this._addEvent("objectRegistered", func);
},
notifyObjectRegistered: function(obj) {
this._raiseEvent("objectRegistered", [obj]);
},
addObjectUnregistered: function(func) {
this._addEvent("objectUnregistered", func);
},
notifyObjectUnregistered: function(obj) {
this._raiseEvent("objectUnregistered", [obj]);
},
addListChanged: function(func) {
this._addEvent("listChanged", func);
},
notifyListChanged: function(obj, property, changes) {
this._raiseEvent("listChanged", [obj, property, changes]);
}
}
Model.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.Model = Model;
Model.registerClass("ExoWeb.Model.Model");
//////////////////////////////////////////////////////////////////////////////////////
function Entity() {
}
Entity.mixin({
toString: function Entity$toString(formatName) {
var format;
if (formatName) {
format = this.constructor.formats[formatName];
if (!format)
throwAndLog(["formatting"], "Invalid format: {0}", arguments);
} else
format = this.constructor.formats.$display || this.constructor.formats.$system;
return format.convert(this);
}
});
Entity.formats = {
$system: new Format({
undefinedString: "",
nullString: "null",
convert: function(obj) {
return $format("{0}|{1}", [obj.meta.type.get_fullName(), obj.meta.id]);
},
convertBack: function(str) {
// indicates "no value", which is distinct from "no selection"
var ids = str.split("|");
var ctor = window[ids[0]];
if (ctor)
return ctor.get(ids[1]);
}
})
}
ExoWeb.Model.Entity = Entity;
Entity.registerClass("ExoWeb.Model.Entity");
//////////////////////////////////////////////////////////////////////////////////////
function Type(model, name, baseType) {
this._rules = {};
this._fullName = name;
this._pool = {};
this._legacyPool = {};
this._counter = 0;
this._properties = {};
this._model = model;
// generate class and constructor
var type = this;
var jstype = window[name];
if (jstype)
throwAndLog(["model"], "'{1}' has already been declared", arguments)
function construct(id) {
if (!disableConstruction) {
if (id) {
var obj = type.get(id);
if (obj)
return obj;
type.register(this, id);
}
else {
type.register(this);
for (var propName in type._properties) {
var prop = type._properties[propName];
if (!prop.get_isStatic() && prop.get_isList()) {
prop.init(this, []);
}
}
}
}
}
var jstype;
if (evalAffectsScope) {
// use eval to generate the type so the function name appears in the debugger
var ctorScript = $format("function {type}(id) { var obj=construct.apply(this, arguments); if(obj) return obj; };" +
"jstype = {type};",
{ type: name });
eval(ctorScript);
}
else {
jstype = construct;
}
this._jstype = window[name] = jstype;
// setup inheritance
this.derivedTypes = [];
var baseJsType;
if (baseType) {
baseJsType = baseType._jstype;
this.baseType = baseType;
baseType.derivedTypes.push(this);
// inherit all shortcut properties that have aleady been defined
for (var propName in baseType._properties)
jstype["$" + propName] = baseType._properties[propName];
}
else {
baseJsType = Entity;
this.baseType = null;
}
disableConstruction = true;
this._jstype.prototype = new baseJsType();
disableConstruction = false;
this._jstype.prototype.constructor = this._jstype;
// formats
var formats = function() { };
formats.prototype = baseJsType.formats;
this._jstype.formats = new formats();
// helpers
jstype.meta = this;
with ({ type: this }) {
jstype.get = function(id) { return type.get(id); };
}
// done...
this._jstype.registerClass(name, baseJsType);
}
Type.prototype = {
newId: function Type$newId() {
return "+c" + this._counter++;
},
register: function Type$register(obj, id) {
obj.meta = new ObjectMeta(this, obj);
if (!id) {
id = this.newId();
obj.meta.isNew = true;
}
else
id = id.toLowerCase();
obj.meta.id = id;
Sys.Observer.makeObservable(obj);
for (var t = this; t; t = t.baseType) {
t._pool[id] = obj;
if (t._known)
t._known.add(obj);
}
this._model.notifyObjectRegistered(obj);
},
changeObjectId: function Type$changeObjectId(oldId, newId) {
oldId = oldId.toLowerCase();
newId = newId.toLowerCase();
var obj = this._pool[oldId];
// TODO: throw exceptions?
if (obj) {
for (var t = this; t; t = t.baseType) {
t._pool[newId] = obj;
delete t._pool[oldId];
t._legacyPool[oldId] = obj;
}
}
obj.meta.id = newId;
},
unregister: function Type$unregister(obj) {
this._model.notifyObjectUnregistered(obj);
for (var t = this; t; t = t.baseType) {
delete t._pool[obj.meta.id];
if (t._known)
t._known.remove(obj);
}
delete obj.meta._obj;
delete obj.meta;
},
get: function Type$get(id) {
id = id.toLowerCase();
return this._pool[id] || this._legacyPool[id];
},
// Gets an array of all objects of this type that have been registered.
// The returned array is observable and collection changed events will be raised
// when new objects are registered or unregistered.
// The array is in no particular order so if you need to sort it, make a copy or use $transform.
known: function Type$known() {
var list = this._known;
if (!list) {
list = this._known = [];
for (id in this._pool)
list.push(this._pool[id]);
Sys.Observer.makeObservable(list);
}
return list;
},
addProperty: function Type$addProperty(def) {
var format = def.format;
if (format && format.constructor === String) {
format = def.type.formats[format];
if (!format)
throwAndLog("model", "Cannot create property {0}.{1} because there is not a '{2}' format defined for {3}", [this._fullName, def.name, def.format, def.type]);
}
var prop = new Property(this, def.name, def.type, def.isList, def.label, format, def.isStatic);
this._properties[def.name] = prop;
// modify jstype to include functionality based on the type definition
function genPropertyShortcut(mtype) {
mtype._jstype["$" + def.name] = prop;
mtype.derivedTypes.forEach(function(t) {
genPropertyShortcut(t);
});
}
genPropertyShortcut(this);
// add members to all instances of this type
//this._jstype.prototype["$" + propName] = prop; // is this useful?
this._jstype.prototype["get_" + def.name] = this._makeGetter(prop, prop.getter);
if (!prop.get_isList())
this._jstype.prototype["set_" + def.name] = this._makeSetter(prop, prop.setter, true);
return prop;
},
_makeGetter: function(receiver, fn) {
return function() {
return fn.call(receiver, this);
}
},
_makeSetter: function(receiver, fn, notifiesChanges) {
var setter = function(val) {
fn.call(receiver, this, val);
};
setter.__notifies = !!notifiesChanges;
return setter;
},
get_model: function() {
return this._model;
},
get_fullName: function() {
return this._fullName;
},
get_jstype: function() {
return this._jstype;
},
property: function(name) {
var p = (name.indexOf(".") >= 0) ? name.substring(0, name.indexOf(".")) : name;
var prop;
for (var t = this; t && !prop; t = t.baseType)
prop = t._properties[p];
if (prop) {
var prop = new PropertyChain(prop);
// evaluate the remainder of the property path
if (name.indexOf(".") >= 0) {
var remainder = name.substring(name.indexOf(".") + 1);
var type = prop.get_jstype().meta;
var children = type.property(remainder);
if (children)
prop.append(children);
else {
// if finding a child property failed then return null
// TODO: should this be more lax and burden consuming
// code with checking the property chain for nulls?
prop = null;
}
}
}
return prop;
},
addRule: function Type$addRule(rule) {
function Type$addRule$init(obj, prop) {
Type$addRule$fn(obj, prop, rule.init ? rule.init : rule.execute);
}
function Type$addRule$execute(obj, prop) {
Type$addRule$fn(obj, prop, rule.execute);
}
function Type$addRule$fn(obj, prop, fn) {
if (rule._isExecuting)
return;
try {
prop.get_containingType().get_model().beginValidation();
rule._isExecuting = true;
log("rule", "executing rule '{0}' that depends on property '{1}'", [rule, prop]);
fn.call(rule, obj);
}
catch (err) {
throwAndLog("rules", "Error running rule '{0}': {1}", [rule, err]);
}
finally {
rule._isExecuting = false;
prop.get_containingType().get_model().endValidation();
}
}
for (var i = 0; i < rule.inputs.length; ++i) {
var input = rule.inputs[i];
var prop = input.property;
if(input.get_dependsOnChange())
prop.addChanged(Type$addRule$execute);
if(input.get_dependsOnInit())
prop.addInited(Type$addRule$init);
(prop instanceof PropertyChain ? prop.lastProperty() : prop)._addRule(rule);
}
},
// Executes all rules that have a particular property as input
executeRules: function Type$executeRules(obj, prop, start) {
var processing;
if(start === undefined)
this._model.beginValidation();
try {
var i = (start ? start : 0);
var rules = prop.get_rules();
if (rules) {
while (processing = (i < rules.length)) {
var rule = rules[i];
if (!rule._isExecuting) {
rule._isExecuting = true;
if (rule.isAsync) {
// run rule asynchronously, and then pickup running next rules afterwards
var _this = this;
log("rule", "executing rule '{0}' that depends on property '{1}'", [rule, prop]);
rule.execute(obj, function(obj) {
rule._isExecuting = false;
_this.executeRules(obj, prop, i + 1);
});
break;
}
else {
try {
log("rule", "executing rule '{0}' that depends on property '{1}'", [rule, prop]);
rule.execute(obj);
}
finally {
rule._isExecuting = false;
}
}
}
++i;
}
}
}
finally {
if (!processing)
this._model.endValidation();
}
},
set_originForNewProperties: function(value) {
this._originForNewProperties = value;
},
get_originForNewProperties: function() {
return this._originForNewProperties;
},
set_origin: function(value) {
this._origin = value;
},
get_origin: function() {
return this._origin;
}
}
Type.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.Type = Type;
Type.registerClass("ExoWeb.Model.Type");
//////////////////////////////////////////////////////////////////////////////////////
/// <remarks>
/// If the interface for this class is changed it should also be changed in
/// PropertyChain, since PropertyChain acts as an aggregation of properties
/// that can be treated as a single property.
/// </remarks>
///////////////////////////////////////////////////////////////////////////////
function Property(containingType, name, jstype, isList, label, format, isStatic) {
this._containingType = containingType;
this._name = name;
this._jstype = jstype;
this._label = label || name.replace(/([^A-Z]+)([A-Z])/g, "$1 $2");
this._format = format;
this._isList = !!isList;
this._isStatic = !!isStatic;
if(containingType.get_originForNewProperties())
this._origin = containingType.get_originForNewProperties();
}
Property.mixin({
rule: function Property$rule(type) {
if (this._rules) {
for (var i = 0; i < this._rules.length; i++) {
var rule = this._rules[i];
if (rule instanceof type)
return rule;
}
}
return null;
},
_addRule: function Property$_addRule(type) {
if (!this._rules)
this._rules = [type];
else
this._rules.push(type);
},
get_rules: function Property$get_rules() {
return this._rules;
},
toString: function() {
return this.get_label();
},
get_containingType: function() {
return this._containingType;
},
get_jstype: function() {
return this._jstype;
},
get_format: function() {
return this._format;
},
get_origin: function() {
return this._origin ? this._origin : this._containingType.get_origin();
},
getter: function(obj) {
return obj[this._name];
},
setter: function(obj, val) {
if (!this.canSetValue(obj, val))
throwAndLog(["model", "entity"], "Cannot set {0}={1}. A value of type {2} was expected", [this._name, val === undefined ? "<undefined>" : val, this._jstype.getName()]);
var old = obj[this._name];
if (old !== val) {
obj[this._name] = val;
// NOTE: property change should be broadcast before rules are run so that if
// any rule causes a roundtrip to the server these changes will be available
this._containingType.get_model().notifyAfterPropertySet(obj, this, val, old);
this._raiseEvent("changed", [obj, this]);
Sys.Observer.raisePropertyChanged(obj, this._name);
}
},
get_isEntityType: function() {
return this.get_jstype().meta && !this._isList;
},
get_isEntityListType: function() {
return this.get_jstype().meta && this._isList;
},
get_isValueType: function() {
return !this.get_jstype().meta;
},
get_isList: function() {
return this._isList;
},
get_isStatic: function() {
return this._isStatic;
},
get_label: function() {
return this._label;
},
get_name: function() {
return this._name;
},
get_path: function() {
return this._isStatic ? (this._containingType.get_fullName() + "." + this._name) : this._name;
},
canSetValue: function Property$canSetValue(obj, val) {
// only allow values of the correct data type to be set in the model
if (val === null || val === undefined)
return true;
if (val.constructor) {
// for entities check base types as well
if (val.constructor.meta) {
for (var valType = val.constructor.meta; valType; valType = valType.baseType)
if (valType._jstype === this._jstype)
return true;
return false;
}
else {
return val.constructor === this._jstype
}
}
else {
var valType;
switch (typeof (val)) {
case "string": valType = String; break;
case "number": valType = Number; break;
case "boolean": valType = Boolean; break;
}
return valType === this._jstype;
};
},
value: function Property$value(obj, val) {
if (arguments.length == 2) {
var setter = obj["set_" + this._name];
// If a generated setter is found then use it instead of observer, since it will emulate observer
// behavior in order to allow application code to call it directly rather than going through the
// observer. Calling the setter in place of observer eliminates unwanted duplicate events.
if (setter && setter.__notifies)
setter.call(obj, val);
else
Sys.Observer.setValue(obj, this._name, val);
}
else {
var target = (this._isStatic ? this._containingType.get_jstype() : obj);
if (target == undefined)
ExoWeb.trace.throwAndLog(["model"],
"Cannot get value for {0}static property \"{1}\" on type \"{2}\": target is undefined.",
[(this._isStatic ? "" : "non-"), this.get_path(), this._containingType.get_fullName()]);
// access directly since the caller might make a distinction between null and undefined
return target[this._name];
}
},
init: function Property$init(obj, val, force) {
var target = (this._isStatic ? this._containingType.get_jstype() : obj);
var curVal = target[this._name];
if (curVal !== undefined && !(force === undefined || force))
return;
target[this._name] = val;
if (val instanceof Array) {
var prop = this;
Sys.Observer.makeObservable(val);
Sys.Observer.addCollectionChanged(val, function(sender, args) {
prop._raiseEvent("changed", [target, prop]);
prop._containingType.get_model().notifyListChanged(target, prop, args.get_changes());
});
}
this._raiseEvent("inited", [target, this]);
},
isInited: function Property$isInited(obj) {
var target = (this._isStatic ? this._containingType.get_jstype() : obj);
var curVal = target[this._name];
return curVal !== undefined;
},
// starts listening for when property.init() is called. Use obj argument to
// optionally filter the events to a specific object
addInited: function Property$addInited(handler, obj) {
var f;
if (obj)
f = function(target, property) {
if (obj === target)
handler(target, property);
}
else
f = handler;
this._addEvent("inited", f);
},
// starts listening for change events on the property. Use obj argument to
// optionally filter the events to a specific object
addChanged: function Property$addChanged(handler, obj) {
var f;
if (obj)
f = function(target, property) {
if (obj === target)
handler(target, property);
}
else
f = handler;
this._addEvent("changed", f);
},
// Adds a rule to the property that will update its value
// based on a calculation.
calculated: function Property$calculated(options) {
var prop = this;
var rootType;
if (options.rootType)
rootType = options.rootType.meta;
else
rootType = prop._containingType;
var inputs;
if (options.basedOn) {
inputs = options.basedOn.map(function(p) {
if (p instanceof Property)
return new RuleInput(p);
var input;
var parts = p.split(" of ");
if(parts.length >= 2) {
input = new RuleInput(Model.property(parts[1], rootType));
var events = parts[0].split(",");
input.set_dependsOnInit(events.indexOf("init") >= 0);
input.set_dependsOnChange(events.indexOf("change") >= 0);
}
else {
input = new RuleInput(Model.property(parts[0], rootType));
input.set_dependsOnInit(true);
}
if (!input.property)
throwAndLog("model", "Calculated property {0}.{1} is based on an invalid property: {2}", [rootType.get_fullName(), prop._name, p]);
return input;
});
}
else {
inputs = Rule.inferInputs(rootType, options.fn);
inputs.forEach(function(input) {
input.set_dependsOnInit(true);
});
}
var rule = {
init: function Property$calculated$init(obj, property) {
if (!prop.isInited(obj) && inputs.every(function(input) { return input.property.isInited(obj); })) {
// init the calculated property
prop.init(obj, options.fn.apply(obj));
}
},
execute: function Property$calculated$recalc(obj) {
if (prop._isList) {
calc = function Property$calculated$calcList(obj) {
// re-calculate the list values
var newList = options.fn.apply(obj);
LazyLoader.load(newList, null, function() {
// compare the new list to the old one to see if changes were made
var curList = prop.value(obj);
if (!curList) {
curList = [];
prop.init(obj, curList);
}
if (newList.length === curList.length) {
var noChanges = true;
for (var i = 0; i < newList.length; ++i) {
if (newList[i] !== curList[i]) {
noChanges = false;
break;
}
}
if (noChanges)
return;
}
// update the current list so observers will receive the change events
curList.beginUpdate();
curList.clear();
curList.addRange(newList);
curList.endUpdate();
});
}
}
else {
var newValue = options.fn.apply(obj);
if(newValue !== prop.value(obj))
Sys.Observer.setValue(obj, prop._name, newValue);
}
},
toString: function() { return "calculation of " + prop._name; }
};
Rule.register(rule, inputs);
// go ahead and calculate this property for all known objects
//Array.forEach(this._containingType.known(), calc);
return this;
}
});
Property.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.Property = Property;
Property.registerClass("ExoWeb.Model.Property");
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Encapsulates the logic required to work with a chain of properties and
/// a root object, allowing interaction with the chain as if it were a
/// single property of the root object.
/// </summary>
///////////////////////////////////////////////////////////////////////////
function PropertyChain(properties) {
this._properties = properties.length ? properties : [properties];
if (this._properties.length == 0)
throwAndLog(["model"], "PropertyChain cannot be zero-length.");
}
PropertyChain.prototype = {
all: function() {
return this._properties;
},
append: function(prop) {
Array.addRange(this._properties, prop.all());
},
// Iterates over all objects along a property chain starting with the root object (obj).
// An optional propFilter can be specified to only iterate over objects on one property
// within the chain.
each: function(obj, callback, propFilter /*, target, p*/) {
if (!callback || typeof (callback) != "function")
throwAndLog(["model"], "Invalid Parameter: callback function");
if (!obj)
throwAndLog(["model"], "Invalid Parameter: source object");
var target = arguments[3] || obj;
var lastProp = null;
for (var p = arguments[4] || 0; p < this._properties.length && (!propFilter || lastProp !== propFilter); p++) {
var prop = this._properties[p];
var enableCallback = (!propFilter || prop === propFilter);
if (target instanceof Array) {
for (var i = 0; i < target.length; ++i) {
if (enableCallback) {
if (callback(target[i], prop) === false)
return false;
}
if (this.each(obj, callback, propFilter, prop.value(target[i]), p + 1) === false)
return false;
}
}
else if (enableCallback) {
if (callback(target, prop) === false) {
return false;
}
}
target = prop.value(target);
lastProp = prop;
}
return true;
},
get_path: function PropertyChain$get_path() {
if (!this._path) {
var parts = [];
if (this._properties[0].get_isStatic())
parts.push(this._properties[0].get_containingType().get_fullName());
this._properties.forEach(function(p) { parts.push(p.get_name()); })
this._path = parts.join(".");
}
return this._path;
},
firstProperty: function() {
return this._properties[0];
},
lastProperty: function() {
return this._properties[this._properties.length - 1];
},
lastTarget: function(obj) {
for (var p = 0; p < this._properties.length - 1; p++) {
var prop = this._properties[p];
obj = prop.value(obj);
}
return obj;
},
prepend: function(prop) {
var newProps = prop.all();
for (var p = newProps.length - 1; p >= 0; p--) {
Array.insert(this._properties, 0, newProps[p]);
}
},
canSetValue: function PropertyChain$canSetValue(obj, value) {
return this.lastProperty().canSetValue(this.lastTarget(obj), value);
},
// Determines if this property chain connects two objects.
// viaProperty is optional but will speed up the search.
connects: function PropertyChain$connects(fromRoot, toObj, viaProperty) {
var connected = false;
this.each(fromRoot, function(target) {
if (target === toObj) {
connected = true;
return false;
}
}, viaProperty);
return connected;
},
// Listens for when property.init() is called on all properties in the chain. Use obj argument to
// optionally filter the events to a specific object
addInited: function PropertyChain$addInited(handler, obj) {
var chain = this;
if (this._properties.length == 1) {
// OPTIMIZATION: no need to search all known objects for single property chains
this._properties[0].addInited(function PropertyChain$_raiseInited$1Prop(sender, property) {
handler(sender, chain);
}, obj);
}
else {
for (var p = 0; p < this._properties.length; p++) {
with ({ priorProp: p == 0 ? undefined : this._properties[p - 1] }) {
if (obj) {
// CASE: using object filter
this._properties[p].addInited(function PropertyChain$_raiseInited$1Obj(sender, property) {
if (chain.isInited(obj))
handler(obj, chain);
}, obj);
}
else {
// CASE: no object filter
this._properties[p].addInited(function PropertyChain$_raiseInited$Multi(sender, property) {
// scan all known objects of this type and raise event for any instance connected
// to the one that sent the event.
Array.forEach(chain.firstProperty().get_containingType().known(), function(known) {
if (chain.connects(known, sender, priorProp) && chain.isInited(known))
handler(known, chain);
});
});
}
}
}
}
},
// starts listening for change events along the property chain on any known instances. Use obj argument to
// optionally filter the events to a specific object
addChanged: function PropertyChain$addChanged(handler, obj) {
var chain = this;
if (this._properties.length == 1) {
// OPTIMIZATION: no need to search all known objects for single property chains
this._properties[0].addChanged(function PropertyChain$_raiseChanged$1Prop(sender, property) {
handler(sender, chain);
}, obj);
}
else {
for (var p = 0; p < this._properties.length; p++) {
with ({ priorProp: p == 0 ? undefined : this._properties[p - 1] }) {
if (obj) {
// CASE: using object filter
this._properties[p].addChanged(function PropertyChain$_raiseChanged$1Obj(sender, property) {
if (chain.connects(obj, sender, priorProp))
handler(obj, chain);
});
}
else {
// CASE: no object filter
this._properties[p].addChanged(function PropertyChain$_raiseChanged$Multi(sender, property) {
// scan all known objects of this type and raise event for any instance connected
// to the one that sent the event.
Array.forEach(chain.firstProperty().get_containingType().known(), function(known) {
if (chain.connects(known, sender, priorProp))
handler(known, chain);
});
});
}
}
}
}
},
// Property pass-through methods
///////////////////////////////////////////////////////////////////////
get_containingType: function PropertyChain$get_containingType() {
return this.firstProperty().get_containingType();
},
get_jstype: function PropertyChain$get_jstype() {
return this.lastProperty().get_jstype();
},
get_format: function PropertyChain$get_format() {
return this.lastProperty().get_format();
},
get_isList: function PropertyChain$get_isList() {
return this.lastProperty().get_isList();
},
get_isStatic: function PropertyChain$get_isStatic() {
// TODO
return this.lastProperty().get_isStatic();
},
get_label: function PropertyChain$get_label() {
return this.lastProperty().get_label();
},
get_name: function PropertyChain$get_name() {
return this.lastProperty().get_name();
},
get_isValueType: function PropertyChain$get_isValueType() {
return this.lastProperty().get_isValueType();
},
get_isEntityType: function PropertyChain$get_isEntityType() {
return this.lastProperty().get_isEntityType();
},
get_isEntityListType: function PropertyChain$get_isEntityListType() {
return this.lastProperty().get_isEntityListType();
},
get_rules: function PropertyChain$_get_rules() {
return this.lastProperty().get_rules();
},
value: function PropertyChain$value(obj, val) {
var target = this.lastTarget(obj);
var prop = this.lastProperty();
if (arguments.length == 2)
prop.value(target, val);
else
return prop.value(target);
},
isInited: function PropertyChain$isInited(obj) {
var allInited = true;
this.each(obj, function(target, property) {
if (!property.isInited(target)) {
allInited = false;
return false;
}
});
return allInited;
},
toString: function() {
return this.get_label();
}
},
ExoWeb.Model.PropertyChain = PropertyChain;
PropertyChain.registerClass("ExoWeb.Model.PropertyChain");
///////////////////////////////////////////////////////////////////////////
function ObjectMeta(type, obj) {
this._obj = obj;
this.type = type;
this._issues = [];
this._propertyIssues = {};
}
ObjectMeta.prototype = {
executeRules: function ObjectMeta$executeRules(prop) {
this.type.get_model()._validatedQueue.push({ sender: this, property: prop.get_name() });
this._raisePropertyValidating(prop.get_name());
this.type.executeRules(this._obj, prop);
},
property: function ObjectMeta$property(propName) {
return this.type.property(propName);
},
clearIssues: function ObjectMeta$clearIssues(origin) {
var issues = this._issues;
for (var i = issues.length - 1; i >= 0; --i) {
var issue = issues[i];
if (issue.get_origin() == origin) {
this._removeIssue(i);
this._raisePropertiesValidated(issue.get_properties());
}
}
},
issueIf: function ObjectMeta$issueIf(issue, condition) {
// always remove and re-add the issue to preserve order
var idx = $.inArray(issue, this._issues);
if (idx >= 0)
this._removeIssue(idx);
if (condition)
this._addIssue(issue);
if ((idx < 0 && condition) || (idx >= 0 && !condition))
this._raisePropertiesValidated(issue.get_properties());
},
_addIssue: function(issue) {
this._issues.push(issue);
// update _propertyIssues
var props = issue.get_properties();
for (var i = 0; i < props.length; ++i) {
var propName = props[i].get_name();
var pi = this._propertyIssues[propName];
if (!pi) {
pi = [];
this._propertyIssues[propName] = pi;
}
pi.push(issue);
}
},
_removeIssue: function(idx) {
var issue = this._issues[idx];
this._issues.splice(idx, 1);
// update _propertyIssues
var props = issue.get_properties();
for (var i = 0; i < props.length; ++i) {
var propName = props[i].get_name();
var pi = this._propertyIssues[propName];
var piIdx = $.inArray(issue, pi);
pi.splice(piIdx, 1);
}
},
issues: function ObjectMeta$issues(prop) {
if (!prop)
return this._issues;
var ret = [];
for (var i = 0; i < this._issues.length; ++i) {
var issue = this._issues[i];
var props = issue.get_properties();
for (var p = 0; p < props.length; ++p) {
if (props[p] == prop) {
ret.push(issue);
break;
}
}
}
return ret;
},
_raisePropertiesValidated: function(properties) {
var queue = this.type.get_model()._validatedQueue;
for (var i = 0; i < properties.length; ++i)
queue.push({ sender: this, property: properties[i].get_name() });
},
addPropertyValidated: function(propName, handler) {
this._addEvent("propertyValidated:" + propName, handler);
},
_raisePropertyValidating: function(propName) {
var queue = this.type.get_model()._validatingQueue;
queue.push({sender: this, propName: propName});
},
addPropertyValidating: function(propName, handler) {
this._addEvent("propertyValidating:" + propName, handler);
},
destroy: function() {
this.type.unregister(this.obj);
}
}
ObjectMeta.mixin(ExoWeb.Functor.eventing);
ExoWeb.Model.ObjectMeta = ObjectMeta;
ObjectMeta.registerClass("ExoWeb.Model.ObjectMeta");
//////////////////////////////////////////////////////////////////////////////////////
function Rule() { }
Rule.register = function Rule$register(rule, inputs, isAsync) {
rule.isAsync = !!isAsync;
rule.inputs = inputs.map(function(item) {
return item instanceof RuleInput ? item : new RuleInput(item);
});
rule.inputs[0].property.get_containingType().addRule(rule);
}
Rule.inferInputs = function Rule$inferInputs(rootType, func) {
var inputs = [];
var match;
while (match = /this\.([a-zA-Z0-9_.]+)/g.exec(func.toString())) {
inputs.push( new RuleInput(rootType.property(match[1]).lastProperty()) );
}
return inputs;
}
ExoWeb.Model.Rule = Rule;
Rule.registerClass("ExoWeb.Model.Rule");
//////////////////////////////////////////////////////////////////////////////////////
function RuleInput(property) {
this.property = property;
}
RuleInput.prototype = {
set_dependsOnInit: function RuleInput$set_dependsOnInit(value) {
this._init = value;
},
get_dependsOnInit: function RuleInput$get_dependsOnInit() {
return this._init === undefined ? false : this._init;
},
set_dependsOnChange: function RuleInput$set_dependsOnChange(value) {
this._change = value;
},
get_dependsOnChange: function RuleInput$get_dependsOnChange() {
return this._change === undefined ? true : this._change;
}
};
ExoWeb.Model.RuleInput = RuleInput;
RuleInput.registerClass("ExoWeb.Model.RuleInput");
//////////////////////////////////////////////////////////////////////////////////////
function RequiredRule(options, properties) {
this.prop = properties[0];
this.err = new RuleIssue(this.prop.get_label() + " is required", properties, this);
Rule.register(this, properties);
}
RequiredRule.prototype = {
execute: function(obj) {
var val = this.prop.value(obj);
if (val instanceof Array) {
obj.meta.issueIf(this.err, val.length == 0);
}
else {
obj.meta.issueIf(this.err, val == null || ($.trim(val.toString()) == ""));
}
},
toString: function() {
return $format("{0}.{1} is required", [this.prop.get_containingType().get_fullName(), this.prop.get_name()]);
}
}
Rule.required = RequiredRule;
//////////////////////////////////////////////////////////////////////////////////////
function RangeRule(options, properties) {
this.prop = properties[0];
this.min = options.min;
this.max = options.max;
var hasMin = (this.min !== undefined && this.min != null);
var hasMax = (this.max !== undefined && this.max != null);
if (hasMin && hasMax) {
this.err = new RuleIssue($format("{prop} must be between {min} and {max}", this), properties, this);
this._test = this._testMinMax;
}
else if (hasMin) {
this.err = new RuleIssue($format("{prop} must be at least {min}", this), properties, this);
this._test = this._testMin;
}
else if (hasMax) {
this.err = new RuleIssue($format("{prop} must no more than {max}", this), properties, this);
this._test = this._testMax;
}
Rule.register(this, properties);
}
RangeRule.prototype = {
execute: function(obj) {
var val = this.prop.value(obj);
obj.meta.issueIf(this.err, this._test(val));
},
_testMinMax: function(val) {
return val < this.min || val > this.max;
},
_testMin: function(val) {
return val < this.min;
},
_testMax: function(val) {
return val > this.max;
},
toString: function() {
return $format("{0}.{1} in range, min: {2}, max: {3}", [this.prop.get_containingType().get_fullName(), this.prop.get_name(), this.min, this.max]);
}
}
Rule.range = RangeRule;
//////////////////////////////////////////////////////////////////////////////////////
function AllowedValuesRule(options, properties) {
var prop = this.prop = properties[0];
this.path = options.source;
this.err = new RuleIssue($format("{prop} has an invalid value", this), properties, this);
Rule.register(this, properties);
this._needsInit = true;
}
AllowedValuesRule.prototype = {
_init: function() {
if (this._needsInit) {
// type is undefined or not loaded
if (LazyLoader.isLoaded(this.prop.get_containingType()))
this._propertyChain = ExoWeb.Model.Model.property(this.path, this.prop.get_containingType());
delete this._needsInit;
}
},
execute: function(obj) {
this._init();
// get the list of allowed values of the property for the given object
var allowed = this.values(obj);
// ignore if allowed values list is undefined (non-existent or unloaded type) or has not been loaded
if (allowed !== undefined && LazyLoader.isLoaded(allowed)) {
// get the current value of the property for the given object
var val = this.prop.value(obj);
// ensure that the value or list of values is in the allowed values list (single and multi-select)
if (val instanceof Array)
obj.meta.issueIf(this.err, !val.every(function(item) { return Array.contains(allowed, item); }));
else
obj.meta.issueIf(this.err, val && !Array.contains(allowed, val));
}
},
propertyChain: function(obj) {
this._init();
return this._propertyChain;
},
values: function(obj) {
this._init();
if (this._propertyChain) {
// get the allowed values from the property chain
return this._propertyChain.value(obj);
}
},
toString: function() {
return $format("{0}.{1} allowed values", [this.prop.get_containingType().get_fullName(), this.prop.get_name()]);
}
}
Rule.allowedValues = AllowedValuesRule;
Property.mixin({
allowedValues: function(options) {
// create a rule that will recalculate allowed values when dependencies change
var source = this.get_name() + "AllowedValues";
var valuesProp = this.get_containingType().addProperty(source, this.get_jstype(), true);
valuesProp.calculated(options);
new AllowedValuesRule({ source: source }, [this]);
}
});
///////////////////////////////////////////////////////////////////////////////////////
function StringLengthRule(options, properties) {
this.prop = properties[0];
this.min = options.min;
this.max = options.max;
var hasMin = (this.min !== undefined && this.min != null);
var hasMax = (this.max !== undefined && this.max != null);
if (hasMin && hasMax) {
this.err = new RuleIssue($format("{prop} must be between {min} and {max} characters", this), properties, this);
this._test = this._testMinMax;
}
else if (hasMin) {
this.err = new RuleIssue($format("{prop} must be at least {min} characters", this), properties, this);
this._test = this._testMin;
}
else if (hasMax) {
this.err = new RuleIssue($format("{prop} must be no more than {max} characters", this), properties, this);
this._test = this._testMax;
}
Rule.register(this, properties);
}
StringLengthRule.prototype = {
execute: function(obj) {
var val = this.prop.value(obj);
obj.meta.issueIf(this.err, this._test(val || ""));
},
_testMinMax: function(val) {
return val.length < this.min || val.length > this.max;
},
_testMin: function(val) {
return val.length < this.min;
},
_testMax: function(val) {
return val.length > this.max;
},
toString: function() {
return $format("{0}.{1} in range, min: {2}, max: {3}", [this.prop.get_containingType().get_fullName(), this.prop.get_name(), this.min, this.max]);
}
}
Rule.stringLength = StringLengthRule;
//////////////////////////////////////////////////////////////////////////////////////
function EventQueue(raise, areEqual) {
this._queueing = 0;
this._queue = [];
this._raise = raise;
this._areEqual = areEqual;
}
EventQueue.prototype = {
startQueueing: function EventQueue$startQueueing() {
++this._queueing;
},
stopQueueing: function EventQueue$stopQueueing() {
if(--this._queueing === 0)
this.raiseQueue();
},
push: function EventQueue$push(item) {
if(this._queueing) {
if (this._areEqual) {
for (var i = 0; i < this._queue.length; ++i) {
if (this._areEqual(item, this._queue[i]))
return;
}
}
this._queue.push(item);
}
else
this._raise(item);
},
raiseQueue: function EventQueue$raiseQueue() {
try {
for (var i = 0; i < this._queue.length; ++i)
this._raise(this._queue[i]);
}
finally {
if (this._queue.length > 0)
this._queue = [];
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
function RuleIssue(message, relatedProperties, origin) {
this._properties = relatedProperties || [];
this._message = message;
this._origin = origin;
}
RuleIssue.prototype = {
get_properties: function() {
return this._properties;
},
get_message: function() {
return this._message;
},
get_origin: function() {
return this._origin;
},
set_origin: function(origin) {
this._origin = origin;
},
equals: function(o) {
return o.property.equals(this.property) && o._message.equals(this._message);
}
}
ExoWeb.Model.RuleIssue = RuleIssue;
RuleIssue.registerClass("ExoWeb.Model.RuleIssue");
//////////////////////////////////////////////////////////////////////////////////////
function FormatIssue(message, invalidValue) {
this._message = message;
this._invalidValue = invalidValue;
}
FormatIssue.prototype = {
get_message: function() {
return this._message;
},
toString: function() {
return this._invalidValue;
},
get_invalidValue: function() {
return this._invalidValue;
}
}
ExoWeb.Model.FormatIssue = FormatIssue;
FormatIssue.registerClass("ExoWeb.Model.FormatIssue");
//////////////////////////////////////////////////////////////////////////////////////
function Format(options) {
this._convert = options.convert;
this._convertBack = options.convertBack;
this._description = options.description;
this._nullString = options.nullString || "";
this._undefinedString = options.undefinedString || "";
}
Format.fromTemplate = (function Format$fromTemplate(convertTemplate) {
return new Format({
convert: function convert(obj) {
if (obj === null || obj === undefined)
return "";
return $format(convertTemplate, obj);
}
});
}).cached({ key: function(convertTemplate) { return convertTemplate; } });
Format.mixin({
convert: function(val) {
if (val === undefined)
return this._undefinedString;
if (val == null)
return this._nullString;
if (val instanceof FormatIssue)
return val.get_invalidValue();
if (!this._convert)
return val;
return this._convert(val);
},
convertBack: function(val) {
if (val == this._nullString)
return null;
if (val == this._undefinedString)
return;
if (val.constructor == String) {
val = val.trim();
if (val.length == 0)
return null;
}
if (!this._convertBack)
return val;
try {
return this._convertBack(val);
}
catch (err) {
return new FormatIssue(this._description ?
"{value} must be formatted as " + this._description :
"{value} is not properly formatted",
val);
}
}
});
ExoWeb.Model.Format = Format;
Format.registerClass("ExoWeb.Model.Format");
// Type Format Strings
/////////////////////////////////////////////////////////////////////////////////////////////////////////
Number.formats = {};
String.formats = {};
Date.formats = {};
TimeSpan.formats = {};
Boolean.formats = {};
//TODO: number formatting include commas
Number.formats.Integer = new Format({
description: "#,###",
convert: function(val) {
return Math.round(val).toString();
},
convertBack: function(str) {
if (!/^([-\+])?(\d+)?\,?(\d+)?\,?(\d+)?\,?(\d+)$/.test(str))
throw "invalid format";
return parseInt(str, 10);
}
});
Number.formats.Float = new Format({
description: "#,###.#",
convert: function(val) {
return val.toString();
},
convertBack: function(str) {
return parseFloat(str);
}
});
Number.formats.$system = Number.formats.Float;
String.formats.Phone = new Format({
description: "###-###-####",
convertBack: function(str) {
if (!/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/.test(str))
throw "invalid format";
return str;
}
});
String.formats.$system = new Format({
convertBack: function(val) {
return val ? $.trim(val) : val;
}
});
Boolean.formats.YesNo = new Format({
convert: function(val) { return val ? "yes" : "no"; },
convertBack: function(str) { return str == "yes"; }
});
Boolean.formats.TrueFalse = new Format({
convert: function(val) { return val ? "true" : "false"; },
convertBack: function(str) { return (str.toLowerCase() == "true"); }
});
Boolean.formats.$system = Boolean.formats.TrueFalse;
Boolean.formats.$display = Boolean.formats.YesNo;
Date.formats.DateTime = new Format({
description: "mm/dd/yyyy hh:mm AM/PM",
convert: function(val) {
return val.format("MM/dd/yyyy h:mm tt");
},
convertBack: function(str) {
var val = Date.parseInvariant(str);
if (val != null)
return val;
throw "invalid date";
}
});
Date.formats.ShortDate = new Format({
description: "mm/dd/yyyy",
convert: function(val) {
return val.format("M/d/yyyy");
},
convertBack: function(str) {
var val = Date.parseInvariant(str);
if (val != null)
return val;
throw "invalid date";
}
});
Date.formats.Time = new Format({
description: "HH:MM AM/PM",
convert: function(val) {
return val.format("h:mm tt");
},
convertBack: function(str) {
var parser = /^(1[0-2]|0?[1-9]):([0-5][0-9]) *(AM?|(PM?))$/i;
var parts = str.match(parser);
if (!parts)
throw "invalid time";
// build new date, start with current data and overwite the time component
var val = new Date();
// hours
if (parts[4])
val.setHours(parseInt(parts[1], 10) + 12); // PM
else
val.setHours(parseInt(parts[1], 10)); // AM
// minutes
val.setMinutes(parseInt(parts[2], 10));
// keep the rest of the time component clean
val.setSeconds(0);
val.setMilliseconds(0);
return val;
}
});
Date.formats.$system = Date.formats.DateTime;
Date.formats.$display = Date.formats.DateTime;
TimeSpan.formats.Meeting = new ExoWeb.Model.Format({
convert: function(val) {
var num;
var label;
if (val.totalHours < 1) {
num = Math.round(val.totalMinutes);
label = "minute";
}
else if (val.totalDays < 1) {
num = Math.round(val.totalHours * 100) / 100;
label = "hour";
}
else {
num = Math.round(val.totalDays * 100) / 100;
label = "day";
}
return num == 1 ? (num + " " + label) : (num + " " + label + "s");
},
convertBack: function(str) {
var parser = /^([0-9]+(\.[0-9]+)?) *(m((inute)?s)?|h((our)?s?)|hr|d((ay)?s)?)$/i;
var parts = str.match(parser);
if (!parts)
throw "invalid format";
var num = parseFloat(parts[1]);
var ms;
if (parts[3].startsWith("m"))
ms = num * 60 * 1000;
else if (parts[3].startsWith("h"))
ms = num * 60 * 60 * 1000;
else if (parts[3].startsWith("d"))
ms = num * 24 * 60 * 60 * 1000;
return new TimeSpan(ms);
}
});
TimeSpan.formats.$display = TimeSpan.formats.Meeting;
TimeSpan.formats.$system = TimeSpan.formats.Meeting; // TODO: implement Exact format
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function LazyLoader() {
}
LazyLoader.eval = function LazyLoader$eval(target, path, successCallback, errorCallback, scopeChain) {
if (!path)
path = [];
else if (!(path instanceof Array))
path = path.split(".");
scopeChain = scopeChain || [window];
target = target || Array.dequeue(scopeChain);
while (path.length > 0) {
var prop = Array.dequeue(path);
if (!LazyLoader.isLoaded(target, prop)) {
LazyLoader.load(target, prop, function() {
var nextTarget = ExoWeb.getValue(target, prop);
if (nextTarget === undefined) {
if (scopeChain.length > 0) {
Array.insert(path, 0, prop);
LazyLoader.eval(Array.dequeue(scopeChain), path, successCallback, errorCallback, scopeChain);
}
else if (errorCallback)
errorCallback("Property is undefined: " + prop);
else
throwAndLog(["lazyLoad"], "Cannot complete property evaluation because a property is undefined: {0}", [prop]);
}
else if (nextTarget != null)
LazyLoader.eval(nextTarget, path, successCallback, errorCallback, []);
else if (successCallback)
successCallback(null);
});
return;
}
else {
var propValue = ExoWeb.getValue(target, prop);
if (propValue === undefined) {
if (scopeChain.length > 0) {
Array.insert(path, 0, prop);
target = Array.dequeue(scopeChain);
}
else {
if (errorCallback)
errorCallback("Property is undefined: " + prop)
else
throwAndLog(["lazyLoad"], "Cannot complete property evaluation because a property is undefined: {0}", [prop]);
return;
}
}
else if (propValue == null) {
if (successCallback)
successCallback(null);
return;
}
else {
if (scopeChain.length > 0)
scopeChain = [];
target = propValue;
}
}
}
// Load final object
if (target != null && !LazyLoader.isLoaded(target))
LazyLoader.load(target, null, function() { successCallback(target); });
else if (successCallback)
successCallback(target);
}
LazyLoader.isLoaded = function LazyLoader$isLoaded(obj, propName) {
if (obj === undefined)
return false;
var reg = obj._lazyLoader;
if (!reg)
return true;
var loader;
if (propName && reg.byProp)
loader = reg.byProp[propName];
if (!loader)
loader = reg.allProps;
return !loader || (loader.isLoaded && obj._lazyLoader.isLoaded(obj, propName));
}
LazyLoader.load = function LazyLoader$load(obj, propName, callback) {
var reg = obj._lazyLoader;
if (!reg) {
if (callback)
callback();
}
else {
var loader;
if (propName && reg.byProp)
loader = reg.byProp[propName];
if (!loader)
loader = reg.allProps;
if (!loader)
throwAndLog(["lazyLoad"], "Attempting to load object but no appropriate loader is registered. object: {0}, property: {1}", [obj, propName]);
loader.load(obj, propName, callback);
}
}
LazyLoader.isRegistered = function LazyLoader$isRegistered(obj, loader, propName) {
var reg = obj._lazyLoader;
if (!reg)
return false;
if (propName)
return reg.byProp && reg.byProp[propName] === loader;
return reg.allProps === loader;
}
LazyLoader.register = function LazyLoader$register(obj, loader, propName) {
var reg = obj._lazyLoader;
if (!reg)
reg = obj._lazyLoader = {};
if (propName) {
if (!reg.byProp)
reg.byProp = {};
reg.byProp[propName] = loader;
}
else
obj._lazyLoader.allProps = loader;
}
LazyLoader.unregister = function LazyLoader$unregister(obj, loader, propName) {
var reg = obj._lazyLoader;
if (!reg)
return;
if (propName) {
delete reg.byProp[propName];
} else if (reg.byProp) {
var allDeleted = true;
for (var p in reg.byProp) {
if (reg.byProp[p] === loader)
delete reg.byProp[p];
else
allDeleted = false;
}
if (allDeleted)
delete reg.byProp;
}
if (reg.allProps === loader)
delete reg.allProps;
if (!reg.byProp && !reg.allProps)
delete obj._lazyLoader;
}
ExoWeb.Model.LazyLoader = LazyLoader;
LazyLoader.registerClass("ExoWeb.Model.LazyLoader");
}
if (Sys && Sys.loader) {
Sys.loader.registerScript("ExoWebModel", null, execute);
}
else {
execute();
}
})();
|
Add "type casting" to property paths. Each step can now include a type cast inside of <> like this: this.Version.EffectiveSections<IepServices>.Service or like this<PrgMeeting>.Date
|
ExoWeb/Client/exoweb.model.js
|
Add "type casting" to property paths. Each step can now include a type cast inside of <> like this: this.Version.EffectiveSections<IepServices>.Service or like this<PrgMeeting>.Date
|
<ide><path>xoWeb/Client/exoweb.model.js
<ide>
<ide> this._validatingQueue = new EventQueue(
<ide> function(e) {
<del> var meta = e.sender;
<add> var meta = e.sender;
<ide> var issues = meta._propertyIssues[e.propName];
<ide> meta._raiseEvent("propertyValidating:" + e.propName, [meta, e.propName])
<ide> },
<ide> function(e) {
<ide> var meta = e.sender;
<ide> var propName = e.property;
<del>
<add>
<ide> var issues = meta._propertyIssues[propName];
<ide> meta._raiseEvent("propertyValidated:" + propName, [meta, issues ? issues : []])
<ide> },
<ide>
<ide> Model.property = function(path, thisType) {
<ide> var part = path.split(".");
<del> var isGlobal = part[0] !== "this";
<add> var firstStep = parsePropertyStep(part[0]);
<add> var isGlobal = firstStep.property !== "this";
<ide>
<ide> var type;
<ide>
<ide> throwAndLog(["model"], "Invalid property path: {0}", [path]);
<ide> }
<ide> else {
<del> if (thisType instanceof Function)
<add> if (firstStep.cast) {
<add> type = window[firstStep.cast];
<add>
<add> if (!type)
<add> throwAndLog("model", "Path '{0}' references an unknown type: {1}", [path, firstStep.cast]);
<add> type = type.meta;
<add> }
<add> else if (thisType instanceof Function)
<ide> type = thisType.meta;
<ide> else
<ide> type = thisType;
<ide>
<ide> Array.dequeue(part);
<ide> }
<del>
<del> return type.property(part.join("."));
<add>
<add> return new PropertyChain(type, part);
<ide> }
<ide>
<ide> Model.prototype = {
<ide> get_jstype: function() {
<ide> return this._jstype;
<ide> },
<del> property: function(name) {
<del> var p = (name.indexOf(".") >= 0) ? name.substring(0, name.indexOf(".")) : name;
<add> property: function(name, thisOnly) {
<add> if (!thisOnly)
<add> return new PropertyChain(this, name);
<ide>
<ide> var prop;
<del> for (var t = this; t && !prop; t = t.baseType)
<del> prop = t._properties[p];
<del>
<del> if (prop) {
<del> var prop = new PropertyChain(prop);
<del>
<del> // evaluate the remainder of the property path
<del> if (name.indexOf(".") >= 0) {
<del> var remainder = name.substring(name.indexOf(".") + 1);
<del>
<del> var type = prop.get_jstype().meta;
<del>
<del> var children = type.property(remainder);
<del> if (children)
<del> prop.append(children);
<del> else {
<del> // if finding a child property failed then return null
<del> // TODO: should this be more lax and burden consuming
<del> // code with checking the property chain for nulls?
<del> prop = null;
<del> }
<del> }
<del> }
<del>
<del> return prop;
<add> for (var t = this; t && !prop; t = t.baseType) {
<add> prop = t._properties[name];
<add>
<add> if (prop)
<add> return prop;
<add> }
<add>
<add> return null;
<ide> },
<ide> addRule: function Type$addRule(rule) {
<ide> function Type$addRule$init(obj, prop) {
<ide> var input = rule.inputs[i];
<ide> var prop = input.property;
<ide>
<del> if(input.get_dependsOnChange())
<add> if (input.get_dependsOnChange())
<ide> prop.addChanged(Type$addRule$execute);
<ide>
<del> if(input.get_dependsOnInit())
<add> if (input.get_dependsOnInit())
<ide> prop.addInited(Type$addRule$init);
<del>
<add>
<ide> (prop instanceof PropertyChain ? prop.lastProperty() : prop)._addRule(rule);
<ide> }
<ide> },
<ide> executeRules: function Type$executeRules(obj, prop, start) {
<ide>
<ide> var processing;
<del>
<del> if(start === undefined)
<add>
<add> if (start === undefined)
<ide> this._model.beginValidation();
<del>
<add>
<ide> try {
<ide> var i = (start ? start : 0);
<ide>
<ide> this._format = format;
<ide> this._isList = !!isList;
<ide> this._isStatic = !!isStatic;
<del>
<del> if(containingType.get_originForNewProperties())
<add>
<add> if (containingType.get_originForNewProperties())
<ide> this._origin = containingType.get_originForNewProperties();
<ide> }
<ide>
<ide> // based on a calculation.
<ide> calculated: function Property$calculated(options) {
<ide> var prop = this;
<del>
<add>
<ide> var rootType;
<ide> if (options.rootType)
<ide> rootType = options.rootType.meta;
<ide>
<ide> var input;
<ide> var parts = p.split(" of ");
<del> if(parts.length >= 2) {
<add> if (parts.length >= 2) {
<ide> input = new RuleInput(Model.property(parts[1], rootType));
<ide> var events = parts[0].split(",");
<del>
<add>
<ide> input.set_dependsOnInit(events.indexOf("init") >= 0);
<ide> input.set_dependsOnChange(events.indexOf("change") >= 0);
<ide> }
<ide> }
<ide> else {
<ide> var newValue = options.fn.apply(obj);
<del> if(newValue !== prop.value(obj))
<add> if (newValue !== prop.value(obj))
<ide> Sys.Observer.setValue(obj, prop._name, newValue);
<ide> }
<ide> },
<ide> /// single property of the root object.
<ide> /// </summary>
<ide> ///////////////////////////////////////////////////////////////////////////
<del> function PropertyChain(properties) {
<del> this._properties = properties.length ? properties : [properties];
<add> function PropertyChain(rootType, path) {
<add> var type = rootType;
<add> var chain = this;
<add>
<add> this._properties = [];
<add> this._filters = [];
<add>
<add> (path instanceof Array ? path : path.split(".")).forEach(function(step) {
<add> var parsed = parsePropertyStep(step);
<add>
<add> if (!parsed)
<add> throwAndLog("model", "Syntax error in property path: {0}", [path]);
<add>
<add> var prop = type.property(parsed.property, true);
<add>
<add> if (!prop)
<add> throwAndLog("model", "Path '{0}' references an unknown property: {1}.{2}", [path, type.get_fullName(), parsed.property]);
<add>
<add> chain._properties.push(prop);
<add>
<add> if (parsed.cast) {
<add> type = type.get_model().type(parsed.cast);
<add>
<add> if (!type)
<add> throwAndLog("model", "Path '{0}' references an unknown type: {1}", [path, parsed.cast]);
<add>
<add> with ({type: type.get_jstype() }) {
<add> chain._filters[chain._properties.length - 1] = function(target) {
<add> return target instanceof type;
<add> };
<add> }
<add> }
<add> else
<add> type = prop.get_jstype().meta;
<add>
<add> });
<ide>
<ide> if (this._properties.length == 0)
<ide> throwAndLog(["model"], "PropertyChain cannot be zero-length.");
<add> }
<add>
<add> function parsePropertyStep(step) {
<add> var parsed = step.match(/^([a-z0-9_]+)(<([a-z0-9_]+)>)?$/i);
<add>
<add> if (!parsed)
<add> return null;
<add>
<add> var result = { property: parsed[1] };
<add>
<add> if (parsed[3])
<add> result.cast = parsed[3];
<add>
<add> return result;
<ide> }
<ide>
<ide> PropertyChain.prototype = {
<ide>
<ide> if (target instanceof Array) {
<ide> for (var i = 0; i < target.length; ++i) {
<del> if (enableCallback) {
<add> if (enableCallback && (!this._filters[p] || this._filters[p](target))) {
<ide> if (callback(target[i], prop) === false)
<ide> return false;
<ide> }
<ide> return false;
<ide> }
<ide> }
<del> else if (enableCallback) {
<del> if (callback(target, prop) === false) {
<add> else if (enableCallback && (!this._filters[p] || this._filters[p](target))) {
<add> if (callback(target, prop) === false)
<ide> return false;
<del> }
<ide> }
<ide>
<ide> target = prop.value(target);
<ide> },
<ide> _raisePropertyValidating: function(propName) {
<ide> var queue = this.type.get_model()._validatingQueue;
<del> queue.push({sender: this, propName: propName});
<add> queue.push({ sender: this, propName: propName });
<ide> },
<ide> addPropertyValidating: function(propName, handler) {
<ide> this._addEvent("propertyValidating:" + propName, handler);
<ide>
<ide> Rule.register = function Rule$register(rule, inputs, isAsync) {
<ide> rule.isAsync = !!isAsync;
<del>
<del> rule.inputs = inputs.map(function(item) {
<add>
<add> rule.inputs = inputs.map(function(item) {
<ide> return item instanceof RuleInput ? item : new RuleInput(item);
<ide> });
<del>
<add>
<ide> rule.inputs[0].property.get_containingType().addRule(rule);
<ide> }
<ide>
<ide> var match;
<ide>
<ide> while (match = /this\.([a-zA-Z0-9_.]+)/g.exec(func.toString())) {
<del> inputs.push( new RuleInput(rootType.property(match[1]).lastProperty()) );
<add> inputs.push(new RuleInput(rootType.property(match[1]).lastProperty()));
<ide> }
<ide>
<ide> return inputs;
<ide> };
<ide> ExoWeb.Model.RuleInput = RuleInput;
<ide> RuleInput.registerClass("ExoWeb.Model.RuleInput");
<del>
<add>
<ide> //////////////////////////////////////////////////////////////////////////////////////
<ide> function RequiredRule(options, properties) {
<ide> this.prop = properties[0];
<ide> ++this._queueing;
<ide> },
<ide> stopQueueing: function EventQueue$stopQueueing() {
<del> if(--this._queueing === 0)
<add> if (--this._queueing === 0)
<ide> this.raiseQueue();
<ide> },
<ide> push: function EventQueue$push(item) {
<del> if(this._queueing) {
<add> if (this._queueing) {
<ide> if (this._areEqual) {
<ide> for (var i = 0; i < this._queue.length; ++i) {
<ide> if (this._areEqual(item, this._queue[i]))
|
|
Java
|
bsd-2-clause
|
22341b96696b214a90228f1e065bf6e62b05fd80
| 0 |
cpythoud/beanmaker,cpythoud/beanmaker
|
package org.beanmaker.util;
import org.dbbeans.util.Money;
import org.dbbeans.util.Strings;
import org.jcodegen.html.ATag;
import org.jcodegen.html.HtmlCodeFragment;
import org.jcodegen.html.InputTag;
import org.jcodegen.html.OptionTag;
import org.jcodegen.html.SelectTag;
import org.jcodegen.html.SpanTag;
import org.jcodegen.html.TableTag;
import org.jcodegen.html.Tag;
import org.jcodegen.html.TbodyTag;
import org.jcodegen.html.TdTag;
import org.jcodegen.html.ThTag;
import org.jcodegen.html.TheadTag;
import org.jcodegen.html.TrTag;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.List;
public abstract class BaseMasterTableView extends BaseView {
protected final String tableId;
protected String tableCssClass = "cctable";
protected String thResetCssClass = null;
protected String tdResetCssClass = null;
protected String thFilterCssClass = null;
protected String tdFilterCssClass = null;
protected String thTitleCssClass = "tb-sort";
protected String thSuperTitleCssClass = null;
protected String formElementFilterCssClass = "tb-filter";
protected String removeFilteringLinkCssClass = "tb-nofilter";
protected Tag removeFilteringHtmlTags = new SpanTag().cssClass("glyphicon glyphicon-remove").title("Remove Filtering");
protected String yesName = "yes";
protected String noName = "no";
protected String yesValue = "A";
protected String noValue = "Z";
protected String yesDisplay = "✔";
protected String noDisplay = "";
protected DateFormat dateFormat = null;
protected DateFormat timeFormat = null;
protected DateFormat datetimeFormat = null;
protected String booleanCenterValueCssClass = "center";
protected int zeroFilledMaxDigits = 18;
protected boolean displayId = false;
protected int columnCount = 2;
protected String noDataMessage = "NO DATA";
public BaseMasterTableView(final String resourceBundleName, final String tableId) {
super(resourceBundleName);
this.tableId = tableId;
}
public String getMasterTable() {
return getTable().child(getHead()).child(getBody()).toString();
}
protected TableTag getTable() {
return new TableTag().cssClass(tableCssClass).id(tableId);
}
protected TheadTag getHead() {
final TheadTag head = new TheadTag();
head.child(getFilterRow());
head.child(getTitleRow());
return head;
}
protected TbodyTag getBody() {
final TbodyTag body = new TbodyTag();
int count = 0;
for (TrTag tr: getData()) {
body.child(tr);
++count;
}
if (count == 0)
body.child(getNoDataAvailableLine());
return body;
}
protected abstract List<TrTag> getData();
protected TrTag getNoDataAvailableLine() {
return getNoDataAvailableLine(noDataMessage);
}
protected TrTag getNoDataAvailableLine(final String message) {
return getNoDataAvailableLine(message, columnCount);
}
protected TrTag getNoDataAvailableLine(final String message, final int columnCount) {
return new TrTag().child(
new TdTag().cssClass(tdResetCssClass)
).child(
new TdTag(message).colspan(columnCount)
);
}
protected TrTag getFilterRow() {
return getDefaultStartOfFilterRow();
}
protected TrTag getTitleRow() {
return getDefaultStartOfTitleRow();
}
protected TrTag getDefaultStartOfFilterRow() {
return new TrTag().child(getRemoveFilteringCellWithLink());
}
protected TrTag getDefaultStartOfTitleRow() {
return new TrTag().child(getRemoveFilteringCell());
}
protected ThTag getRemoveFilteringCellWithLink() {
return getRemoveFilteringCell().child(
new ATag().href("#").cssClass(removeFilteringLinkCssClass).child(removeFilteringHtmlTags)
);
}
protected ThTag getRemoveFilteringCell() {
final ThTag cell = new ThTag();
if (thResetCssClass != null)
cell.cssClass(thResetCssClass);
return cell;
}
protected ThTag getTableFilterCell() {
final ThTag cell = new ThTag();
if (thFilterCssClass != null)
cell.cssClass(thFilterCssClass);
return cell;
}
protected ThTag getStringFilterCell(final String name) {
return getTableFilterCell().child(
new InputTag(InputTag.InputType.TEXT).name("tb-" + name).cssClass(formElementFilterCssClass).attribute("autocomplete", "off")
);
}
protected ThTag getBooleanFilterCell(final String name) {
return getTableFilterCell().child(
new SelectTag().name("tb-" + name).cssClass(formElementFilterCssClass).child(
new OptionTag("", "").selected()
).child(
new OptionTag(yesName, yesValue)
).child(
new OptionTag(noName, noValue)
)
);
}
protected ThTag getTitleCell(final String name) {
return getTitleCell(name, resourceBundle.getString(name));
}
protected ThTag getTitleCell(final String name, final String adhocTitle) {
return new ThTag(adhocTitle).cssClass(thTitleCssClass).attribute("data-sort-class", "tb-" + name);
}
protected ThTag getTitleCell(final String name, final Tag adhocTitle) {
return new ThTag().cssClass(thTitleCssClass).attribute("data-sort-class", "tb-" + name).child(adhocTitle);
}
protected TrTag getTableLine() {
final TrTag line = new TrTag();
line.child(getTableCellForRemoveFilteringPlaceholder());
return line;
}
protected TdTag getTableCellForRemoveFilteringPlaceholder() {
final TdTag cell = new TdTag();
if (tdResetCssClass != null)
cell.cssClass(tdResetCssClass);
return cell;
}
protected TdTag getTableCell(final String name, final Tag content) {
return getTableCell(name, content, null);
}
protected TdTag getTableCell(final String name, final Tag content, final String extraCssClasses) {
return new TdTag().child(content).cssClass(getTableCellCssClasses(name, extraCssClasses));
}
protected TdTag getTableCell(final String name, final String value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final String value, final String extraCssClasses) {
return new TdTag(value).cssClass(getTableCellCssClasses(name, extraCssClasses));
}
private String getTableCellCssClasses(final String name, final String extraCssClasses) {
return "tb-" + name + (extraCssClasses == null ? "" : " " + extraCssClasses);
}
protected TdTag getTableCell(final String name, final Date value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Date value, final String extraCssClasses) {
if (value == null)
return getTableCell(name, "");
if (dateFormat == null)
dateFormat = DateFormat.getDateInstance();
return getTableCell(name, dateFormat.format(value), extraCssClasses).attribute("data-sort-value", value.toString());
}
protected TdTag getTableCell(final String name, final Time value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Time value, final String extraCssClasses) {
if (value == null)
return getTableCell(name, "");
if (timeFormat == null)
timeFormat = DateFormat.getTimeInstance();
return getTableCell(name, timeFormat.format(value), extraCssClasses).attribute("data-sort-value", value.toString());
}
protected TdTag getTableCell(final String name, final Timestamp value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Timestamp value, final String extraCssClasses) {
if (value == null)
return getTableCell(name, "");
if (datetimeFormat == null)
datetimeFormat = DateFormat.getDateTimeInstance();
return getTableCell(name, datetimeFormat.format(value), extraCssClasses).attribute("data-sort-value", value.toString());
}
protected TdTag getTableCell(final String name, final boolean value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final boolean value, final String extraCssClasses) {
if (value)
return getTableBooleanCell(name, yesDisplay, yesValue, extraCssClasses);
return getTableBooleanCell(name, noDisplay, noValue, extraCssClasses);
}
protected TdTag getTableBooleanCell(final String name, final String value, final String sortnfilter) {
return getTableBooleanCell(name, value, sortnfilter, null);
}
protected TdTag getTableBooleanCell(
final String name,
final String value,
final String sortnfilter,
final String extraCssClasses)
{
return decorateBooleanCell(new TdTag(value), name, sortnfilter, extraCssClasses);
}
protected TdTag getTableBooleanCell(final String name, final Tag value, final String sortnfilter) {
return getTableBooleanCell(name, value, sortnfilter, null);
}
protected TdTag getTableBooleanCell(
final String name,
final Tag value,
final String sortnfilter,
final String extraCssClasses)
{
return decorateBooleanCell(new TdTag().child(value), name, sortnfilter, extraCssClasses);
}
protected TdTag getTableBooleanCell(final String name, final HtmlCodeFragment value, final String sortnfilter) {
return getTableBooleanCell(name, value, sortnfilter, null);
}
protected TdTag getTableBooleanCell(
final String name,
final HtmlCodeFragment value,
final String sortnfilter,
final String extraCssClasses) {
return decorateBooleanCell(new TdTag().addCodeFragment(value), name, sortnfilter, extraCssClasses);
}
private TdTag decorateBooleanCell(
final TdTag cell,
final String name,
final String sortnfilter,
final String extraCssClasses)
{
return cell
.cssClass(booleanCenterValueCssClass + " " + getTableCellCssClasses(name, extraCssClasses))
.attribute("data-filter-value", sortnfilter).attribute("data-sort-value", sortnfilter);
}
protected TdTag getTableCell(final String name, final long value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final long value, final String extraCssClasses) {
return getTableCell(name, Long.toString(value), extraCssClasses).attribute("data-sort-value", Strings.zeroFill(value, zeroFilledMaxDigits));
}
protected TdTag getTableCell(final String name, final Money value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Money value, final String extraCssClasses) {
return getTableCell(name, value.toString(), extraCssClasses).attribute("data-sort-value", Strings.zeroFill(value.getVal(), zeroFilledMaxDigits));
}
protected TdTag getTableCell(final String name, final HtmlCodeFragment content) {
return getTableCell(name, content, null);
}
protected TdTag getTableCell(final String name, final HtmlCodeFragment content, final String extraCssClasses) {
return new TdTag().addCodeFragment(content).cssClass(getTableCellCssClasses(name, extraCssClasses));
}
protected TheadTag getThreeLineHead() {
final TheadTag head = new TheadTag();
head.child(getFilterRow());
head.child(getSuperTitleRow());
head.child(getTitleRow());
return head;
}
protected TrTag getSuperTitleRow() {
return getDefautStartSuperTitleRow();
}
protected TrTag getDefautStartSuperTitleRow() {
final TrTag row = new TrTag().child(new ThTag().cssClass(thResetCssClass));
if (displayId)
row.child(new ThTag());
return row;
}
protected ThTag getMultiColTitle(final String text, final int colspan) {
final ThTag multiColTitle = new ThTag(text).colspan(colspan);
if (thSuperTitleCssClass != null)
multiColTitle.cssClass(thSuperTitleCssClass);
return multiColTitle;
}
}
|
src/org/beanmaker/util/BaseMasterTableView.java
|
package org.beanmaker.util;
import org.dbbeans.util.Money;
import org.dbbeans.util.Strings;
import org.jcodegen.html.ATag;
import org.jcodegen.html.HtmlCodeFragment;
import org.jcodegen.html.InputTag;
import org.jcodegen.html.OptionTag;
import org.jcodegen.html.SelectTag;
import org.jcodegen.html.SpanTag;
import org.jcodegen.html.TableTag;
import org.jcodegen.html.Tag;
import org.jcodegen.html.TbodyTag;
import org.jcodegen.html.TdTag;
import org.jcodegen.html.ThTag;
import org.jcodegen.html.TheadTag;
import org.jcodegen.html.TrTag;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.List;
public abstract class BaseMasterTableView extends BaseView {
protected final String tableId;
protected String tableCssClass = "cctable";
protected String thResetCssClass = null;
protected String tdResetCssClass = null;
protected String thFilterCssClass = null;
protected String tdFilterCssClass = null;
protected String thTitleCssClass = "tb-sort";
protected String thSuperTitleCssClass = null;
protected String formElementFilterCssClass = "tb-filter";
protected String removeFilteringLinkCssClass = "tb-nofilter";
protected Tag removeFilteringHtmlTags = new SpanTag().cssClass("glyphicon glyphicon-remove").title("Remove Filtering");
protected String yesName = "yes";
protected String noName = "no";
protected String yesValue = "A";
protected String noValue = "Z";
protected String yesDisplay = "✔";
protected String noDisplay = "";
protected DateFormat dateFormat = null;
protected DateFormat timeFormat = null;
protected DateFormat datetimeFormat = null;
protected String booleanCenterValueCssClass = "center";
protected int zeroFilledMaxDigits = 18;
protected boolean displayId = false;
protected int columnCount = 2;
protected String noDataMessage = "NO DATA";
public BaseMasterTableView(final String resourceBundleName, final String tableId) {
super(resourceBundleName);
this.tableId = tableId;
}
public String getMasterTable() {
return getTable().child(getHead()).child(getBody()).toString();
}
protected TableTag getTable() {
return new TableTag().cssClass(tableCssClass).id(tableId);
}
protected TheadTag getHead() {
final TheadTag head = new TheadTag();
head.child(getFilterRow());
head.child(getTitleRow());
return head;
}
protected TbodyTag getBody() {
final TbodyTag body = new TbodyTag();
int count = 0;
for (TrTag tr: getData()) {
body.child(tr);
++count;
}
if (count == 0)
body.child(getNoDataAvailableLine());
return body;
}
protected abstract List<TrTag> getData();
protected TrTag getNoDataAvailableLine() {
return getNoDataAvailableLine(noDataMessage);
}
protected TrTag getNoDataAvailableLine(final String message) {
return getNoDataAvailableLine(message, columnCount);
}
protected TrTag getNoDataAvailableLine(final String message, final int columnCount) {
return new TrTag().child(
new TdTag().cssClass(tdResetCssClass)
).child(
new TdTag(message).colspan(columnCount)
);
}
protected TrTag getFilterRow() {
return getDefaultStartOfFilterRow();
}
protected TrTag getTitleRow() {
return getDefaultStartOfTitleRow();
}
protected TrTag getDefaultStartOfFilterRow() {
return new TrTag().child(getRemoveFilteringCellWithLink());
}
protected TrTag getDefaultStartOfTitleRow() {
return new TrTag().child(getRemoveFilteringCell());
}
protected ThTag getRemoveFilteringCellWithLink() {
return getRemoveFilteringCell().child(
new ATag().href("#").cssClass(removeFilteringLinkCssClass).child(removeFilteringHtmlTags)
);
}
protected ThTag getRemoveFilteringCell() {
final ThTag cell = new ThTag();
if (thResetCssClass != null)
cell.cssClass(thResetCssClass);
return cell;
}
protected ThTag getTableFilterCell() {
final ThTag cell = new ThTag();
if (thFilterCssClass != null)
cell.cssClass(thFilterCssClass);
return cell;
}
protected ThTag getStringFilterCell(final String name) {
return getTableFilterCell().child(
new InputTag(InputTag.InputType.TEXT).name("tb-" + name).cssClass(formElementFilterCssClass).attribute("autocomplete", "off")
);
}
protected ThTag getBooleanFilterCell(final String name) {
return getTableFilterCell().child(
new SelectTag().name(name).cssClass(formElementFilterCssClass).child(
new OptionTag("", "").selected()
).child(
new OptionTag(yesName, yesValue)
).child(
new OptionTag(noName, noValue)
)
);
}
protected ThTag getTitleCell(final String name) {
return getTitleCell(name, resourceBundle.getString(name));
}
protected ThTag getTitleCell(final String name, final String adhocTitle) {
return new ThTag(adhocTitle).cssClass(thTitleCssClass).attribute("data-sort-class", "tb-" + name);
}
protected ThTag getTitleCell(final String name, final Tag adhocTitle) {
return new ThTag().cssClass(thTitleCssClass).attribute("data-sort-class", "tb-" + name).child(adhocTitle);
}
protected TrTag getTableLine() {
final TrTag line = new TrTag();
line.child(getTableCellForRemoveFilteringPlaceholder());
return line;
}
protected TdTag getTableCellForRemoveFilteringPlaceholder() {
final TdTag cell = new TdTag();
if (tdResetCssClass != null)
cell.cssClass(tdResetCssClass);
return cell;
}
protected TdTag getTableCell(final String name, final Tag content) {
return getTableCell(name, content, null);
}
protected TdTag getTableCell(final String name, final Tag content, final String extraCssClasses) {
return new TdTag().child(content).cssClass(getTableCellCssClasses(name, extraCssClasses));
}
protected TdTag getTableCell(final String name, final String value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final String value, final String extraCssClasses) {
return new TdTag(value).cssClass(getTableCellCssClasses(name, extraCssClasses));
}
private String getTableCellCssClasses(final String name, final String extraCssClasses) {
return "tb-" + name + (extraCssClasses == null ? "" : " " + extraCssClasses);
}
protected TdTag getTableCell(final String name, final Date value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Date value, final String extraCssClasses) {
if (value == null)
return getTableCell(name, "");
if (dateFormat == null)
dateFormat = DateFormat.getDateInstance();
return getTableCell(name, dateFormat.format(value), extraCssClasses).attribute("data-sort-value", value.toString());
}
protected TdTag getTableCell(final String name, final Time value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Time value, final String extraCssClasses) {
if (value == null)
return getTableCell(name, "");
if (timeFormat == null)
timeFormat = DateFormat.getTimeInstance();
return getTableCell(name, timeFormat.format(value), extraCssClasses).attribute("data-sort-value", value.toString());
}
protected TdTag getTableCell(final String name, final Timestamp value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Timestamp value, final String extraCssClasses) {
if (value == null)
return getTableCell(name, "");
if (datetimeFormat == null)
datetimeFormat = DateFormat.getDateTimeInstance();
return getTableCell(name, datetimeFormat.format(value), extraCssClasses).attribute("data-sort-value", value.toString());
}
protected TdTag getTableCell(final String name, final boolean value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final boolean value, final String extraCssClasses) {
if (value)
return getTableBooleanCell(name, yesDisplay, yesValue, extraCssClasses);
return getTableBooleanCell(name, noDisplay, noValue, extraCssClasses);
}
protected TdTag getTableBooleanCell(final String name, final String value, final String sortnfilter) {
return getTableBooleanCell(name, value, sortnfilter, null);
}
protected TdTag getTableBooleanCell(final String name, final String value, final String sortnfilter, final String extraCssClasses) {
return new TdTag(value).cssClass(booleanCenterValueCssClass + " " + getTableCellCssClasses(name, extraCssClasses))
.attribute("data-filter-value", sortnfilter).attribute("data-sort-value", sortnfilter);
}
protected TdTag getTableCell(final String name, final long value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final long value, final String extraCssClasses) {
return getTableCell(name, Long.toString(value), extraCssClasses).attribute("data-sort-value", Strings.zeroFill(value, zeroFilledMaxDigits));
}
protected TdTag getTableCell(final String name, final Money value) {
return getTableCell(name, value, null);
}
protected TdTag getTableCell(final String name, final Money value, final String extraCssClasses) {
return getTableCell(name, value.toString(), extraCssClasses).attribute("data-sort-value", Strings.zeroFill(value.getVal(), zeroFilledMaxDigits));
}
protected TdTag getTableCell(final String name, final HtmlCodeFragment content) {
return getTableCell(name, content, null);
}
protected TdTag getTableCell(final String name, final HtmlCodeFragment content, final String extraCssClasses) {
return new TdTag().addCodeFragment(content).cssClass(getTableCellCssClasses(name, extraCssClasses));
}
protected TheadTag getThreeLineHead() {
final TheadTag head = new TheadTag();
head.child(getFilterRow());
head.child(getSuperTitleRow());
head.child(getTitleRow());
return head;
}
protected TrTag getSuperTitleRow() {
return getDefautStartSuperTitleRow();
}
protected TrTag getDefautStartSuperTitleRow() {
final TrTag row = new TrTag().child(new ThTag().cssClass(thResetCssClass));
if (displayId)
row.child(new ThTag());
return row;
}
protected ThTag getMultiColTitle(final String text, final int colspan) {
final ThTag multiColTitle = new ThTag(text).colspan(colspan);
if (thSuperTitleCssClass != null)
multiColTitle.cssClass(thSuperTitleCssClass);
return multiColTitle;
}
}
|
Added capacity to use Tags and HtmlCodeFragments in creating boolean type TableCells, and corrected a bug in getBooleanFilterCell (tb- prefix missing from field name).
|
src/org/beanmaker/util/BaseMasterTableView.java
|
Added capacity to use Tags and HtmlCodeFragments in creating boolean type TableCells, and corrected a bug in getBooleanFilterCell (tb- prefix missing from field name).
|
<ide><path>rc/org/beanmaker/util/BaseMasterTableView.java
<ide>
<ide> protected ThTag getBooleanFilterCell(final String name) {
<ide> return getTableFilterCell().child(
<del> new SelectTag().name(name).cssClass(formElementFilterCssClass).child(
<add> new SelectTag().name("tb-" + name).cssClass(formElementFilterCssClass).child(
<ide> new OptionTag("", "").selected()
<ide> ).child(
<ide> new OptionTag(yesName, yesValue)
<ide> return getTableBooleanCell(name, value, sortnfilter, null);
<ide> }
<ide>
<del> protected TdTag getTableBooleanCell(final String name, final String value, final String sortnfilter, final String extraCssClasses) {
<del> return new TdTag(value).cssClass(booleanCenterValueCssClass + " " + getTableCellCssClasses(name, extraCssClasses))
<add> protected TdTag getTableBooleanCell(
<add> final String name,
<add> final String value,
<add> final String sortnfilter,
<add> final String extraCssClasses)
<add> {
<add> return decorateBooleanCell(new TdTag(value), name, sortnfilter, extraCssClasses);
<add> }
<add>
<add> protected TdTag getTableBooleanCell(final String name, final Tag value, final String sortnfilter) {
<add> return getTableBooleanCell(name, value, sortnfilter, null);
<add> }
<add>
<add> protected TdTag getTableBooleanCell(
<add> final String name,
<add> final Tag value,
<add> final String sortnfilter,
<add> final String extraCssClasses)
<add> {
<add> return decorateBooleanCell(new TdTag().child(value), name, sortnfilter, extraCssClasses);
<add> }
<add>
<add> protected TdTag getTableBooleanCell(final String name, final HtmlCodeFragment value, final String sortnfilter) {
<add> return getTableBooleanCell(name, value, sortnfilter, null);
<add> }
<add>
<add> protected TdTag getTableBooleanCell(
<add> final String name,
<add> final HtmlCodeFragment value,
<add> final String sortnfilter,
<add> final String extraCssClasses) {
<add> return decorateBooleanCell(new TdTag().addCodeFragment(value), name, sortnfilter, extraCssClasses);
<add> }
<add>
<add> private TdTag decorateBooleanCell(
<add> final TdTag cell,
<add> final String name,
<add> final String sortnfilter,
<add> final String extraCssClasses)
<add> {
<add> return cell
<add> .cssClass(booleanCenterValueCssClass + " " + getTableCellCssClasses(name, extraCssClasses))
<ide> .attribute("data-filter-value", sortnfilter).attribute("data-sort-value", sortnfilter);
<ide> }
<ide>
|
|
Java
|
mit
|
2a30a3a7c058954804dff023b858a89fd27bae2e
| 0 |
thyrlian/stolpersteine,Stolpersteine/stolpersteine-android
|
package com.dreiri.stolpersteine.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
import com.dreiri.stolpersteine.R;
public class BioActivity extends Activity {
WebView browser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_web);
Intent intent = getIntent();
final String bioData = intent.getStringExtra("bioData");
browser = (WebView) findViewById(R.id.webkit);
browser.getSettings().setBuiltInZoomControls(true);
browser.getSettings().setDisplayZoomControls(false);
String mimeType = "text/html";
String encoding = "utf-8";
browser.loadData(bioData, mimeType, encoding);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bio, menu);
return true;
}
}
|
src/com/dreiri/stolpersteine/activities/BioActivity.java
|
package com.dreiri.stolpersteine.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
import com.dreiri.stolpersteine.R;
public class BioActivity extends Activity {
WebView browser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_web);
Intent intent = getIntent();
final String bioData = intent.getStringExtra("bioData");
browser = (WebView) findViewById(R.id.webkit);
browser.getSettings().setBuiltInZoomControls(true);
browser.getSettings().setDisplayZoomControls(false);
Thread downloadThread = new Thread() {
@Override
public void run() {
super.run();
String mimeType = "text/html";
String encoding = "utf-8";
browser.loadData(bioData, mimeType, encoding);
}
};
downloadThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bio, menu);
return true;
}
}
|
Removed unused download thread, and moved browser.loadData back to UI thread
|
src/com/dreiri/stolpersteine/activities/BioActivity.java
|
Removed unused download thread, and moved browser.loadData back to UI thread
|
<ide><path>rc/com/dreiri/stolpersteine/activities/BioActivity.java
<ide> browser = (WebView) findViewById(R.id.webkit);
<ide> browser.getSettings().setBuiltInZoomControls(true);
<ide> browser.getSettings().setDisplayZoomControls(false);
<del>
<del> Thread downloadThread = new Thread() {
<del> @Override
<del> public void run() {
<del> super.run();
<del> String mimeType = "text/html";
<del> String encoding = "utf-8";
<del> browser.loadData(bioData, mimeType, encoding);
<del> }
<del> };
<del> downloadThread.start();
<add> String mimeType = "text/html";
<add> String encoding = "utf-8";
<add> browser.loadData(bioData, mimeType, encoding);
<ide> }
<ide>
<ide> @Override
|
|
Java
|
agpl-3.0
|
ef32d555baabf163f450ab916a74c6cc110e226a
| 0 |
fpempresa/fpempresa,fpempresa/fpempresa,fpempresa/fpempresa,fpempresa/fpempresa,fpempresa/fpempresa,fpempresa/fpempresa,fpempresa/fpempresa,fpempresa/fpempresa
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.logongas.fpempresa.service.populate;
import es.logongas.fpempresa.modelo.centro.Centro;
import es.logongas.fpempresa.modelo.centro.EstadoCentro;
import es.logongas.fpempresa.modelo.comun.Contacto;
import es.logongas.fpempresa.modelo.comun.geo.Direccion;
import es.logongas.fpempresa.modelo.comun.geo.Municipio;
import es.logongas.fpempresa.modelo.comun.geo.Provincia;
import es.logongas.fpempresa.modelo.comun.usuario.EstadoUsuario;
import es.logongas.fpempresa.modelo.comun.usuario.TipoUsuario;
import es.logongas.fpempresa.modelo.comun.usuario.Usuario;
import es.logongas.fpempresa.modelo.educacion.Ciclo;
import es.logongas.fpempresa.modelo.empresa.Empresa;
import es.logongas.fpempresa.modelo.titulado.ExperienciaLaboral;
import es.logongas.fpempresa.modelo.titulado.FormacionAcademica;
import es.logongas.fpempresa.modelo.titulado.Idioma;
import es.logongas.fpempresa.modelo.titulado.NivelIdioma;
import es.logongas.fpempresa.modelo.titulado.TipoDocumento;
import es.logongas.fpempresa.modelo.titulado.TipoFormacionAcademica;
import es.logongas.fpempresa.modelo.titulado.Titulado;
import es.logongas.fpempresa.modelo.titulado.TituloIdioma;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
/**
* Genera nombre aleatorios a partir de una lista de nombres.
*
* @author logongas
*/
public class GeneradorDatosAleatorios {
private GeneradorDatosAleatorios() {
}
static final public Usuario createUsuarioAleatorio(TipoUsuario tipoUsuario) {
Random random = new Random(System.currentTimeMillis());
String[] correos = {"gmail.com", "yahoo.com", "hotmail.com"};
Usuario usuario = new Usuario();
String ape1 = GeneradorDatosAleatorios.getApellidoPersona();
String ape2 = GeneradorDatosAleatorios.getApellidoPersona();
String nombre = GeneradorDatosAleatorios.getNombrePersona();
String email = ape1.substring(0, 3) + ape2.substring(0, 3) + nombre.substring(0, 3) + random.nextInt(9999) + "@" + GeneradorDatosAleatorios.getAleatorio(correos);
usuario.setApellidos(ape1 + " " + ape2);
usuario.setNombre(nombre);
usuario.setEmail(email.toLowerCase());
usuario.setPassword("a");
usuario.setTipoUsuario(tipoUsuario);
usuario.setEstadoUsuario(EstadoUsuario.ACEPTADO);
return usuario;
}
static final public Centro createCentroAleatorio() {
Centro centro = new Centro();
centro.setEstadoCentro(EstadoCentro.PERTENECE_A_FPEMPRESA);
centro.setNombre(GeneradorDatosAleatorios.getNombreCentroAleatorio());
centro.setDireccion(createDireccionAleatoria());
centro.setContacto(createContactoCentroAleatorio(centro));
return centro;
}
static final public Empresa createEmpresaAleatoria(Centro centro) {
String[] tiposEmpresa = {"Sociedad Anonima", "Sociedad Limitada", "Cooperativa", "Sociedad Laboral"};
String nombreEmpresa = GeneradorDatosAleatorios.getNombreEmpresa() + " " + GeneradorDatosAleatorios.getApellidoPersona();
Empresa empresa = new Empresa();
empresa.setNombreComercial(nombreEmpresa);
empresa.setRazonSocial(nombreEmpresa + " " + GeneradorDatosAleatorios.getAleatorio(tiposEmpresa));
empresa.setDireccion(createDireccionAleatoria());
if (centro!=null) {
empresa.getDireccion().setMunicipio(centro.getDireccion().getMunicipio());
}
empresa.setContacto(createContactoEmpresaAleatorio(empresa));
empresa.setCentro(centro);
empresa.setCif(GeneradorDatosAleatorios.getCif());
return empresa;
}
static final public Titulado createTituladoAleatorio() {
Titulado titulado = new Titulado();
String[] permisosConducir = {"A", "A", "B", "B", "C1", "C", null, null, null, null, null, null, null, null, null, null, null, null, null, null};
titulado.setDireccion(createDireccionAleatoria());
titulado.setFechaNacimiento(GeneradorDatosAleatorios.getFecha(18, 35));
titulado.setTipoDocumento(TipoDocumento.NIF_NIE);
titulado.setNumeroDocumento(GeneradorDatosAleatorios.getNif());
titulado.setPermisosConducir(GeneradorDatosAleatorios.getAleatorio(permisosConducir));
titulado.setTelefono(GeneradorDatosAleatorios.getTelefono());
titulado.setTelefonoAlternativo(GeneradorDatosAleatorios.getTelefono());
titulado.setResumen(GeneradorDatosAleatorios.getResumenPersona());
return titulado;
}
static final public Direccion createDireccionAleatoria() {
Direccion direccion = new Direccion();
direccion.setDatosDireccion(GeneradorDatosAleatorios.getDireccion());
direccion.setMunicipio(getMunicipioAleatorio());
return direccion;
}
static final public Contacto createContactoAleatorio() {
Contacto contacto = new Contacto();
contacto.setPersona(GeneradorDatosAleatorios.getNombrePersona() + " " + GeneradorDatosAleatorios.getApellidoPersona() + " " + GeneradorDatosAleatorios.getApellidoPersona());
contacto.setTelefono(GeneradorDatosAleatorios.getTelefono());
contacto.setFax(GeneradorDatosAleatorios.getTelefono());
return contacto;
}
static final public TituloIdioma createTituloIdiomaAleatorio(Titulado titulado) {
TituloIdioma tituloIdioma =new TituloIdioma();
String[] otroIdioma = {"Chino", "Ruso", "Armenio", "Italiano", "Árabe", "Griego", "Japonés"};
tituloIdioma.setTitulado(titulado);
tituloIdioma.setFecha(GeneradorDatosAleatorios.getFecha(0, 5));
tituloIdioma.setIdioma((Idioma) GeneradorDatosAleatorios.getAleatorio(Idioma.values()));
if (tituloIdioma.getIdioma() == Idioma.OTRO) {
tituloIdioma.setOtroIdioma(GeneradorDatosAleatorios.getAleatorio(otroIdioma));
}
tituloIdioma.setNivelIdioma((NivelIdioma) GeneradorDatosAleatorios.getAleatorio(NivelIdioma.values()));
return tituloIdioma;
}
static final public FormacionAcademica createFormacionAcademicaAleatoria(Titulado titulado) {
FormacionAcademica formacionAcademica = new FormacionAcademica();
TipoFormacionAcademica[] tipoFormacionAcademica = {TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.TITULO_UNIVERSITARIO};
Boolean[] nuevoCentro = {false, false, false, false, false, false, true};
formacionAcademica.setTitulado(titulado);
formacionAcademica.setTipoFormacionAcademica((TipoFormacionAcademica) GeneradorDatosAleatorios.getAleatorio(tipoFormacionAcademica));
formacionAcademica.setFecha(GeneradorDatosAleatorios.getFecha(0, 5));
switch (formacionAcademica.getTipoFormacionAcademica()) {
case CICLO_FORMATIVO:
Ciclo ciclo=new Ciclo();
ciclo.setIdCiclo(10);
formacionAcademica.setCiclo(ciclo);
Centro centro=new Centro();
centro.setIdCentro(-1);
formacionAcademica.setCentro(centro);
formacionAcademica.setOtroCentro(GeneradorDatosAleatorios.getNombreCentroAleatorio());
break;
case TITULO_UNIVERSITARIO:
formacionAcademica.setOtroCentro("Universidad de " + getProvinciaAleatoria().getDescripcion());
formacionAcademica.setOtroTitulo(GeneradorDatosAleatorios.getCarreraUniversitaria());
break;
default:
throw new RuntimeException("Tipo de formacion academicas no soportado:" + formacionAcademica.getTipoFormacionAcademica());
}
return formacionAcademica;
}
static final public ExperienciaLaboral createExperienciaLaboralAleatoria(Titulado titulado) {
ExperienciaLaboral experienciaLaboral = new ExperienciaLaboral();
Random random = new Random();
Calendar calendarFin = new GregorianCalendar();
calendarFin.setTime(GeneradorDatosAleatorios.getFecha(0, 5));
calendarFin.set(Calendar.MILLISECOND, 0);
calendarFin.set(Calendar.SECOND, 0);
calendarFin.set(Calendar.MINUTE, 0);
calendarFin.set(Calendar.HOUR_OF_DAY, 0);
Date fechaFin = calendarFin.getTime();
Calendar calendarInicio = new GregorianCalendar();
calendarInicio.setTime(fechaFin);
calendarInicio.add(Calendar.DATE, -(random.nextInt(90) + 7));
calendarInicio.set(Calendar.MILLISECOND, 0);
calendarInicio.set(Calendar.SECOND, 0);
calendarInicio.set(Calendar.MINUTE, 0);
calendarInicio.set(Calendar.HOUR_OF_DAY, 0);
Date fechaInicio = calendarInicio.getTime();
experienciaLaboral.setTitulado(titulado);
experienciaLaboral.setFechaInicio(fechaInicio);
experienciaLaboral.setFechaFin(fechaFin);
experienciaLaboral.setNombreEmpresa(GeneradorDatosAleatorios.getNombreEmpresa());
experienciaLaboral.setPuestoTrabajo(GeneradorDatosAleatorios.getNombrePuestoTrabajo());
experienciaLaboral.setDescripcion("Realizar trabajos relacionados con el puesto de trabajo de " + experienciaLaboral.getPuestoTrabajo());
return experienciaLaboral;
}
static final public Provincia getProvinciaAleatoria() {
Random random = new Random();
int i = random.nextInt(provincias.length);
String nombre = provincias[i];
Provincia provincia = new Provincia();
provincia.setIdProvincia(i + 1);
provincia.setDescripcion(nombre);
return provincia;
}
static final public Municipio getMunicipioAleatorio() {
Random random = new Random();
int i = random.nextInt(municipios.length);
String nombre = municipios[i];
Municipio municipio = new Municipio();
municipio.setIdMunicipio(i + 1);
municipio.setDescripcion(nombre);
municipio.setProvincia(getProvinciaAleatoria());
return municipio;
}
static final public Municipio getMunicipioAleatorio(Provincia provincia) {
Municipio municipio = getMunicipioAleatorio();
municipio.setProvincia(provincia);
return municipio;
}
static final public Contacto createContactoEmpresaAleatorio(Empresa empresa) {
Contacto contacto = createContactoAleatorio();
contacto.setUrl("http://www." + empresa.getNombreComercial().replaceAll("\\s+", "").toLowerCase() + ".com");
contacto.setEmail("info@" + empresa.getNombreComercial().replaceAll("\\s+", "").toLowerCase() + ".com");
return contacto;
}
static final public Contacto createContactoCentroAleatorio(Centro centro) {
Contacto contacto = createContactoAleatorio();
contacto.setUrl("http://www." + centro.getNombre().replaceAll("\\s+", "").toLowerCase() + ".com");
contacto.setEmail("secretaria@" + centro.getNombre().replaceAll("\\s+", "").toLowerCase() + ".com");
return contacto;
}
static final public String getNombreEmpresa() {
return getAleatorio(empresas);
}
static final public String getNombrePersona() {
return getAleatorio(nombres);
}
static final public String getApellidoPersona() {
return getAleatorio(apellidos);
}
static final public String getDireccion() {
return getAleatorio(direcciones);
}
static final public String getNombrePuestoTrabajo() {
return getAleatorio(puestoTrabajo);
}
static final public String getNombreCentroAleatorio() {
String[] tiposCentro = {"IES", "CIPFP"};
String[] tiposPersona = {"Pintor", "", "", "Botanico", "Literato", "Arquitecto", "Poeta", "Escultor", "", "", "", "", "", "", ""};
return getAleatorio(tiposCentro) + " " + getAleatorio(tiposPersona) + " " + getNombrePersona() + " " + getApellidoPersona();
}
static final public String getTelefono() {
Random random = new Random();
Integer[] prefix = {9, 6};
return getAleatorio(prefix) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1);
}
static final public String getResumenPersona() {
String[] pre = {"Especializado en", "Puedo", "Me gusta", "Mi pasión es", "Mi hobby es", "Disfruto al", "Siempre he querido", "He trabajo en"};
return getAleatorio(pre) + " " + getAleatorio(verbo) + " " + getAleatorio(concepto) + " " + getAleatorio(complemento);
}
static final public String getCarreraUniversitaria() {
return getAleatorio(carreras);
}
static final public String getCif() {
Random random = new Random();
String[] letrasIniciales = {"C", "D", "F", "G", "J", "N", "P", "Q", "R", "S", "V", "W"};
String cifSinLetra = getAleatorio(letrasIniciales) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1);
return cifSinLetra + getLetraCif(cifSinLetra);
}
static final public String getNif() {
Random random = new Random();
String[] letrasIniciales = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "X"};
String nifSinLetra = getAleatorio(letrasIniciales) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1);
return nifSinLetra + getLetraNif(nifSinLetra);
}
private static String getLetraNif(String nifSinLetra) {
String letras = "TRWAGMYFPDXBNJZSQVHLCKE";
int valor;
if (nifSinLetra.startsWith("X")) {
//Es un NIE
valor = Integer.parseInt(nifSinLetra.substring(1, nifSinLetra.length() - 1));
} else if (nifSinLetra.startsWith("Y")) {
//Es un NIE
valor = 10000000 + Integer.parseInt(nifSinLetra.substring(1, nifSinLetra.length() - 1));
} else if (nifSinLetra.startsWith("Z")) {
//Es un NIE
valor = 20000000 + Integer.parseInt(nifSinLetra.substring(1, nifSinLetra.length() - 1));
} else {
//Es un NIF
valor = Integer.parseInt(nifSinLetra.substring(0, nifSinLetra.length() - 1));
}
return "" + letras.charAt(valor % 23);
}
private static String getLetraCif(String cifSinLetra) {
int a = 0;
a = a + Integer.parseInt(cifSinLetra.substring(2, 3));
a = a + Integer.parseInt(cifSinLetra.substring(4, 5));
a = a + Integer.parseInt(cifSinLetra.substring(6, 7));
int b = 0;
for (int i = 0; i < 4; i++) {
String parcialB = ((Integer.parseInt(cifSinLetra.substring((i * 2) + 1, (i * 2) + 2)) * 2) + "") + "0";
b = b + Integer.parseInt(parcialB.substring(0, 1)) + Integer.parseInt(parcialB.substring(1, 2));
}
int c = a + b;
String sc = ("0" + c);
int e = Integer.parseInt(sc.substring(sc.length() - 1));
int d = e;
if (e != 0) {
d = 10 - e;
}
String[] codigos = {"J", "A", "B", "C", "D", "E", "F", "G", "H", "I"};
return codigos[d];
}
static final public Date getFecha(int minAnyos, int maxAnyos) {
Random random = new Random();
Calendar calendar = new GregorianCalendar();
if (minAnyos == maxAnyos) {
calendar.add(Calendar.YEAR, -minAnyos);
} else {
calendar.add(Calendar.YEAR, -(minAnyos + random.nextInt(maxAnyos - minAnyos)));
}
calendar.add(Calendar.DATE, -random.nextInt(360));
return calendar.getTime();
}
static final public String getAleatorio(String[] datos) {
Random random = new Random();
return datos[random.nextInt(datos.length)];
}
static final public Object getAleatorio(Object[] datos) {
Random random = new Random();
return datos[random.nextInt(datos.length)];
}
static final public <T> T getAleatorio(List<T> datos) {
Random random = new Random();
return datos.get(random.nextInt(datos.size()));
}
private static final String[] municipios = {"Tobarra",
"Valdeganga",
"Vianos",
"Villa de Ves",
"Villalgordo del Júcar",
"Villamalea",
"Villapalacios",
"Villarrobledo",
"Villatoya",
"Villavaliente",
"Villaverde de Guadalimar",
"Viveros",
"Yeste",
"Pozo Cañada",
"Adsubia",
"Agost",
"Agres",
"Aigües",
"Albatera",
"Alcalalí",
"Alcocer de Planes",
"Alcoleja",
"Alcoy/Alcoi",
"Alfafara",
"Alfàs del Pi",
"Algorfa",
"Algueña",
"Alicante/Alacant",
"Almoradí",
"Almudaina",
"Alqueria",
"Altea",
"Aspe",
"Balones",
"Banyeres de Mariola",
"Benasau",
"Beneixama",
"Benejúzar"
};
private static final String[] provincias = {"Araba/Álava",
"Albacete",
"Alicante/Alacant",
"Almería",
"Ávila",
"Badajoz",
"Balears, Illes",
"Barcelona",
"Burgos",
"Cáceres",
"Cádiz",
"Castellón/Castelló",
"Ciudad Real",
"Córdoba",
"Coruña, A",
"Cuenca",
"Girona",
"Granada",
"Guadalajara",
"Gipuzkoa",
"Huelva",
"Huesca",
"Jaén",
"León",
"Lleida",
"Rioja, La",
"Lugo",
"Madrid",
"Málaga",
"Murcia",
"Navarra",
"Ourense",
"Asturias",
"Palencia",
"Palmas, Las",
"Pontevedra",
"Salamanca",
"Santa Cruz de Tenerife",
"Cantabria",
"Segovia",
"Sevilla",
"Soria",
"Tarragona",
"Teruel",
"Toledo",
"Valencia/Valéncia",
"Valladolid",
"Bizkaia",
"Zamora",
"Zaragoza",
"Ceuta",
"Melilla"};
private static final String[] direcciones = {"c/San Vicente Ferrer, 15 bajo ",
"c/ San Pedro, 12",
"c/ Luis Oliag, 69 1",
"c/ Sanchis Sivera, 18 bajo",
"Av.Naquera, 44-1",
"Crta. CV416, s/n",
"c/ Escultor Beltran 11",
"c/ Altamira, 49",
"c/ Blasco Ibañez, 192",
"c/ Enginyer Balaguer 76-2-14",
"Av. San Lorenzo, 39",
"c/ Cervantes, 3 ",
"Av. Gandia, 45",
"Escultor Aixa, 12-2",
"Urb. Los lagos 519 - Apt. Correos 69",
"c/Dos de Mayo, 92 bajo ",
"c/ Jacinto Benavent, 11",
"Av. Beato Ferreres 1-1-4 ",
"Cami del Molí 9 bajo ",
"c/ Alqueria de Soria, 40-4",
"c/ Benifairó, 1-1 ",
"c/ Sueca 25 ",
"c/ San Isidro Labrador, s/n",
"c/ Senda del Secanet 44-8",
"c/ Dr.Fleming, 30",
"Av. Real de Madrid, 20 ",
"Camino Moncada, 64-9 B ",
"c/ Bona Bista, 4 ",
"c/ Manuel Lopez Varela, 32",
"C/ Luis Vives, 18 ",
"c/ La Sangre, s/n (Edif Mcpal)",
"c/ Alberola 21",
"Carrer del Mig 18-1",
"c/ Pintor Tarrasó, 62-1 ",
"c/Virgen de Campanar 15-10ª ",
"Ronda Joan Fuster, 6 bajo",
"C/ Remedios Lizondo, 1",
"c/ Benimamet, 20",
"c/ Juan de Juanes 3 bajo",
"c/ Reyes Católicos, 38",
"carrer moreretes 1 ",
"c/ San Antonio 4",
"Pl.Españoleto 2",
"C/ San Antoni, 4-b",
"País Valencià, 17",
"Jaime de Olit, 31 ",
"C/ Mercado, 15 bajo ",
"PASSATGE REIX, 1-3-14",
"C/ Felipe Valls, 175",
"Avd. Alqueria de Roc, 12-24",
"Avd. Censals 22",
"Avd. Passeig del Oficis 28",
"Avd. Ausias March, 40",
"c/Padre Fullana, 8 ",
"c/Xátiva, 24 bajo ",
"c/Constitución, 35 bajo ",
"c/ Salvador Botella, 33 -1-1",
"Avd. La Bastida, 12",
"C/ Leonardo Bonet, 8-1-3",
"Avd. Mayor Santa Catalina, 11",
"Avd. Lluis Suñer, 28 B",
"Avd. Puchadeta del Sord, 16",
"Avda. Corts Valencianes, 26",
"P.Ind El Brosquil, c/ 11 Parc 12A",
"c/ Jubilados, 19-2",
"Virgen Dolores, 9-bajo ",
"Plaza Cabanilles, 4-2-6",
"C/ Cirene, 12 arpart. B8",
"Avd. Encarnacio 2",
"Avd. Ausias March, 28",
"Avd. Medico Marcial Bernat, 10",
"Avd. San Sebastián, 102",
"Avd. Botánico Cabanilles, 5",
"c/ La Savina, 1-D",
"c/ Senia de la Llobera, s/n Nave 1",
"c/ Hernan Cortes 3 ",
"P.Germanies, 93 Local B ",
"c/Llauri, 25 bajo ",
"c/ Dr Fleming, 57",
"C/ Vergeret, 1-4-18",
"Pais Valenciano, 36",
"c/San Rafael 74 ",
"C/ Ribera Baixa, 128",
"Menendez Pelayo, 19",
"C/ Pintor Sorolla, 5",
"c/ Vte.Andrés Estellés, 31 ",
"c/ 25 d`aBril, 11 ",
"c/ San Cristobal, 10",
"Plaça Major, 3",
"Almeria, 8 pta 6",
"c/Joaquin Sorolla 49 - 5",
"c/ Maestro Amblar, 6",
"c/ Padre Feijó, 4 Esc 1 pta 20",
"c/ Marques de Montortal, 45b",
"c/ Cumbres Mayores, 4-2 ",
"carrtera LLiria 113-4 ",
"c/ Maestro Rodrigo, 37 bajo",
"C/ Picassent 7-10",
"Av.Diputación, 1-bajo",
"Plaça del Poble 1",
"Calle Marines 2-12",
"c/Colon, 6 bajo ",
"c/ Pintor Sorolla, 12 ",
"c/ Torrent, 5-bajo",
"c/ Benemerita Guardia Civil, 19 ",
"c/ Mancomunidad Alto Turia, s/n",
"Plaza de España, 1",
"c/ San Vicente Mártir, 16 Entr 1 pta 6",
"c/ Camino de Vera s/n ",
"c/ De la Ribera, 16",
"c/ Jose Todolí Cucarella 52",
"c/ Valencia, 2",
"c/ Ermita, 36 ",
"c/ San Antonio, 42",
"c/ Antigua Via del Ferrocarril s/n",
"c/ Vicent Tomas Marti, 14-9",
"c/ Cervantes, 16-b",
"Calle Acacias, 14 ",
"Plaza La Cenia, 7 bajo ",
"c/ Padre Gil Sendra, 17 bajo",
"c/ Virgen del Socorro, 10-8",
"c/ Madre Vedruna, 15-B",
"c/ Puente, 4",
"C/ Mestre Serrano, 20",
"c/ Elionor Ripoll, 13",
"c/ Tauleta, 15",
"c/ Pinedo al Mar 27 bajo ",
"C/ Bonavista 11",
"Av. Joanot Martorel, 18",
"Pza.Músico Espí 9-5ª ",
"c/Morella, 11 Bajo A ",
"c/ Pais Valencia, 14-2º-3ª",
"Av.de Pera, 3",
"c/ Fco. Valldecabres, 2-7",
"c/ Actor Rambal, 29-1",
"c/ Lepanto, 50",
"c/ Carles Salvador 3",
"Ronda Sindic A. Albuixech, 121",
"c/ Maestro Palau, 98",
"c/ Antonio Suarez, 22-14",
"Carrera Malilla, 80 bajo",
"c/Llano de Zaidia, 17 bajo ",
"c/Abadia 20 ",
"c/ Magdalena, 87 bajo ",
"c/Caja de Ahorros, 7 ",
"c/ San Miquel 15",
"c/Almas, 19",
"c/ Parroco Miguel Tarin 30",
"c/Blasco Ibañez, 38",
"c/ Pino 8 ",
"c/Gandia, 26 ",
"c/Vicente Puchol, 16-1 ",
"c/Blasco Ibáñez, 72 bajo ",
"Avda.Dr.Waskman, 58 bajo ",
"c/ D. Enrique Olmos Cercós, 2B-2",
"c/Raquel Payá, 14 ",
"c/ Pintor Sorolla 13",
"c/ Jaume I, 36 bajo Izda",
"c/Angel, 21 ",
"Avda.Pais Valencia, 15 bajo ",
"Av Museros, 25-46",
"c/ Del Foc, 1",
"c/ Turia 21",
"c/Pinar, 5 bajo ",
"c/ Gran Via Ramon y Cajal 13 bajo",
"c/ La Tauleta, 36",
"c/ Libertad, 10",
"c/Buen Suceso, 3-6ª ",
"c/ Arzobispo Olaechea, 39 B",
"c/ Rio Genil, 4-11 ",
"c/ Jaume I, 17 ",
"c/ Dr. Fleming, 7-1",
"Plaza Antonio Machado 8",
"Plaza Las Escuelas, 22-3",
"Plaza San Cayetano, 10-12",
"Avd. Cid, 3-3-9",
"Plaza Favara, 4",
"Plaza Luz Casanova, 11-bajo C",
"Plaza Alcalde Miguel Domingo, 3",
"Plaza Gandia, 21",
"Plaza Mar, 17",
"Pza Don Manuel Garcia Izquierdo, S/",
"Avda Del Sur 22 - 3 - 5",
"c/ José Iturbi, 27-B",
"Plaza Coronel Lopez Aparicio 4"};
private static final String[] empresas = {"kubs",
"mirecker",
"anahi",
"appeph",
"sanle",
"intioga",
"hebar",
"hudon",
"walsk",
"medinp",
"wiresta",
"pfiensol",
"bree",
"banciter",
"iton",
"stan",
"watics",
"pohorp",
"capuscona",
"beling",
"quervarix",
"coman",
"fraltalko",
"brius",
"yamatho",
"valpopars",
"catita",
"branatin",
"natic",
"wespen",
"eves",
"abeng",
"teles",
"bankyo",
"grum",
"tsung",
"amenom",
"serne",
"aluxon",
"sheles",
"angost",
"yoki",
"mizai",
"happgno",
"vivers",
"daita",
"danz",
"authan",
"scommurow",
"tectohn",
"teill",
"frants",
"costpatsu",
"badide",
"reldancon",
"bhans",
"urbaisl",
"pacitsch",
"carti",
"symars",
"shorts",
"irie",
"meran",
"medic",
"dare",
"negank",
"hinos",
"cumb",
"ahon",
"nagan",
"facom",
"wace",
"sindskair",
"worizern",
"sumin",
"hancianey",
"poling",
"urbalern",
"moubillo",
"aurkersto",
"hyds",
"eures",
"nidtral",
"amber",
"haria",
"cumins",
"ecommit",
"alpos",
"cond",
"capir",
"assai",
"synt",
"avin",
"holay",
"glar",
"hewirles",
"ters",
"parminer",
"nage",
"kellima"};
private static final String[] nombres = {"Antonio",
"Jose",
"Manuel",
"Francisco",
"Juan",
"David",
"Jose Antonio",
"Jose Luis",
"Javier",
"Francisco Javier",
"Jesus",
"Daniel",
"Carlos",
"Miguel",
"Alejandro",
"Jose Manuel",
"Rafael",
"Pedro",
"Angel",
"Miguel Angel",
"Jose Maria",
"Fernando",
"Pablo",
"Luis",
"Sergio",
"Jorge",
"Alberto",
"Juan Carlos",
"Juan Jose",
"Alvaro",
"Diego",
"Adrian",
"Juan Antonio",
"Raul",
"Enrique",
"Ramon",
"Vicente",
"Ivan",
"Ruben",
"Oscar",
"Andres",
"Joaquin",
"Juan Manuel",
"Santiago",
"Eduardo",
"Victor",
"Roberto",
"Jaime",
"Francisco Jose",
"Mario",
"Ignacio",
"Alfonso",
"Salvador",
"Ricardo",
"Marcos",
"Jordi",
"Emilio",
"Julian",
"Julio",
"Guillermo",
"Gabriel",
"Tomas",
"Agustin",
"Jose Miguel",
"Marc",
"Gonzalo",
"Felix",
"Jose Ramon",
"Mohamed",
"Hugo",
"Joan",
"Ismael",
"Nicolas",
"Cristian",
"Samuel",
"Mariano",
"Josep",
"Domingo",
"Juan Francisco",
"Aitor",
"Martin",
"Alfredo",
"Sebastian",
"Jose Carlos",
"Felipe",
"Hector",
"Cesar",
"Jose Angel",
"Jose Ignacio",
"Victor Manuel",
"Iker",
"Gregorio",
"Luis Miguel",
"Alex",
"Jose Francisco",
"Juan Luis",
"Rodrigo",
"Albert",
"Xavier",
"Lorenzo",
"Maria Carmen",
"Maria",
"Carmen",
"Josefa",
"Isabel",
"Ana maria",
"Maria Pilar",
"Maria Dolores",
"Maria Teresa",
"Ana",
"Laura",
"Francisca",
"Maria Angeles",
"Cristina",
"Antonia",
"Marta",
"Dolores",
"Maria Isabel",
"Maria Jose",
"Lucia",
"Maria Luisa",
"Pilar",
"Elena",
"Concepcion",
"Sara",
"Paula",
"Manuela",
"Mercedes",
"Rosa Maria",
"Raquel",
"Maria Jesus",
"Juana",
"Rosario",
"Teresa",
"Encarnacion",
"Beatriz",
"Nuria",
"Silvia",
"Julia",
"Rosa",
"Montserrat",
"Patricia",
"Irene",
"Andrea",
"Rocio",
"Monica",
"Alba",
"Maria mar",
"Angela",
"Sonia",
"Alicia",
"Sandra",
"Susana",
"Margarita",
"Marina",
"Yolanda",
"Maria Josefa",
"Natalia",
"Maria Rosario",
"Inmaculada",
"Eva",
"Maria Mercedes",
"Esther",
"Ana isabel",
"Angeles",
"Noelia",
"Claudia",
"Veronica",
"Amparo",
"Maria rosa",
"Carolina",
"Maria Victoria",
"Carla",
"Eva maria",
"Maria Concepcion",
"Nerea",
"Lorena",
"Ana Belen",
"Victoria",
"Miriam",
"Maria Elena",
"Sofia",
"Catalina",
"Ines",
"Maria Antonia",
"Consuelo",
"Emilia",
"Maria Nieves",
"Lidia",
"Luisa",
"Gloria",
"Celia",
"Olga",
"Aurora",
"Esperanza",
"Josefina",
"Maria soledad",
"Milagros",
"Maria cristina",
"Daniela"};
private static final String[] apellidos = {"Garcia",
"Gonzalez",
"Rodriguez",
"Fernandez",
"Lopez",
"Martinez",
"Sanchez",
"Perez",
"Gomez",
"Martin",
"Jimenez",
"Ruiz",
"Hernandez",
"Diaz",
"Moreno",
"Alvarez",
"Romero",
"Alonso",
"Gutierrez",
"Navarro",
"Torres",
"Dominguez",
"Vazquez",
"Ramos",
"Gil",
"Ramirez",
"Serrano",
"Blanco",
"Molina",
"Suarez",
"Morales",
"Ortega",
"Delgado",
"Castro",
"Ortiz",
"Rubio",
"Marin",
"Sanz",
"Iglesias",
"Medina",
"Garrido",
"Cortes",
"Santos",
"Castillo",
"Lozano",
"Guerrero",
"Cano",
"Prieto",
"Mendez",
"Calvo",
"Cruz",
"Gallego",
"Vidal",
"Leon",
"Marquez",
"Herrera",
"Flores",
"Cabrera",
"Campos",
"Vega",
"Fuentes",
"Diez",
"Carrasco",
"Caballero",
"Nieto",
"Reyes",
"Aguilar",
"Pascual",
"Herrero",
"Santana",
"Lorenzo",
"Hidalgo",
"Montero",
"Gimenez",
"Ferrer",
"Duran",
"Santiago",
"Vicente",
"Benitez",
"Mora",
"Arias",
"Vargas",
"Carmona",
"Crespo",
"Roman",
"Pastor",
"Soto",
"Saez",
"Velasco",
"Moya",
"Soler",
"Esteban",
"Parra",
"Bravo",
"Gallardo",
"Rojas"};
private static final String[] verbo = {"acelerar",
"acoplar",
"adoptar",
"agregar",
"alimentar",
"articular",
"analizar",
"complementar",
"cultivar",
"conceptualizar",
"compatibilizar",
"contextualizar",
"construir",
"desarrollar",
"desplegar",
"diseñar",
"encapsular",
"engranar",
"ensamblar",
"escalar",
"estimular",
"evaluar",
"evolucionar",
"explotar",
"extender",
"facilitar",
"favorecer",
"generar",
"gestionar",
"habilitar",
"incubar",
"implementar",
"impulsar",
"incentivar",
"integrar",
"maximizar",
"nivelar",
"reconvertir",
"re-inventar",
"reformatear",
"objetivizar",
"optimizar",
"orquestar",
"propulsar",
"racionalizar",
"sinergizar",
"sintetizar",
"sistematizar",
"transformar",
"visualizar"};
private static final String[] concepto = {"actuaciones",
"ajustes",
"aplicaciones",
"asociaciones",
"arquitecturas",
"infraestructuras",
"iniciativas",
"canales",
"comunidades",
"conectividades",
"contenidos",
"convergencias",
"dinámicas",
"esquemas",
"estructuras",
"experiencias",
"funcionalidades",
"interfaces",
"mecanismos",
"mercados",
"metodologías",
"modelos",
"nichos",
"indicadores",
"paradigmas",
"plataformas",
"políticas",
"portales",
"protocolos",
"proyecciones",
"proyectos",
"redes",
"relaciones",
"servicios electrónicos",
"sinergias",
"sistemas",
"soluciones",
"tendencias",
"tecnologías",
"topologías",
"transiciones",
"transposiciones",
"usuarios"};
private static final String[] complemento = {"de activación",
"afines",
"de banda ancha",
"business-to-business",
"business-to-consumer",
"conceptuales",
"con capacidades dinámicas",
"con capacidades Web",
"de código abierto",
"de colaboración",
"de contorno",
"de convergencia",
"de distribución",
"escalables",
"eficientes",
"globales",
"granulares",
"de iniciativa",
"llave en mano",
"a medida",
"modulares",
"con interactividad",
"one-to-one",
"perimetrales",
"de personalización",
"de tipo plug-and-play",
"punto-com",
"con proactividad",
"de re-ingeniería",
"de re-posicionamiento",
"del sector privado",
"de atención al cliente",
"de tecnología punta",
"en tiempo real",
"de redes sociales",
"sostenibles",
"de la web 2.0",
"transparentes",
"de transición",
"de última generación",
"con centro en el usuario",
"de valor añadido",
"verticales",
"de visión periférica",
"virales",
"virtuales"};
private final static String[] carreras = {"Arqueología",
"Artes Escénicas",
"Bellas Artes",
"Conservación - Restauración de Bienes Culturales",
"Danza",
"Diseño",
"Estudios Literarios",
"Filosofía",
"Fotografía",
"Geografía",
"Astronomía y Astrofísica",
"Biología",
"Bioquímica",
"Biotecnología",
"Ciencia y Tecnología de los Alimentos",
"Ciencias Ambientales",
"Ciencias Biomédicas",
"Ciencias del Mar",
"Ciencias Experimentales",
"Enología",
"Ciencias Biomédicas",
"Ciencias de la Actividad Física y del Deporte",
"Enfermería",
"Farmacia",
"Fisioterapia",
"Logopedia",
"Medicina",
"Nutrición Humana y Dietética",
"Odontología",
"Óptica y Optometría",
"Administración y Dirección de Empresas",
"Antropología",
"Asistencia en Dirección",
"Ciencias del Trabajo y Recursos Humanos",
"Ciencias del Transporte y la Logística",
"Ciencias Políticas y de la Administración Pública",
"Comercio",
"Comunicación Audiovisual",
"Contabilidad y Finanzas",
"Criminología",
"Arquitectura",
"Diseño y Desarrollo de videojuegos",
"Ingeniería Aeroespacial",
"Ingeniería Agroambiental",
"Ingeniería Alimentaria",
"Ingeniería Ambiental",
"Ingeniería Biomédica",
"Ingeniería de Caminos, Canales y Puertos",
"Ingeniería de la Edificación",
"Ingeniería de la Energía"};
private static final String[] puestoTrabajo = {"Acomodador/a",
"Acomodador/a-acomodador/a",
"Actor/actriz",
"Administracion-atencion al cliente",
"Administracion-auxiliar administrativo/a",
"Administracion-auxiliar contable",
"Administracion-becaria asuntos sociales",
"Administracion-botones",
"Administracion-codificador de datos",
"Administracion-direccion y gestion empresarial",
"Administracion-oficial administrativo/a",
"Administracion-ordenanza",
"Administracion-otro personal de oficina",
"Administracion-otros",
"Administracion-profesional de contabilidad",
"Administracion-recepcionista",
"Administracion-secretariado",
"Agente censal",
"Agente de igualdad",
"Agente desarrollo local",
"Agente forestal",
"Agente forestal-agente forestal",
"Agente forestal-viverista",
"Agente judicial",
"Agricultor/a",
"Alfarero/a",
"Animador/a sociocultural",
"Apicultor/a",
"Archivero/a",
"Archivero/a-archivero/a",
"Archivero/a-auxiliar de archivo",
"Archivero/a-ayudante de archivo",
"Artesano/a",
"Asesor",
"Asesor de imagen",
"Asesor en prl",
"Asesor fiscal y tributario",
"Asesor juridico",
"Asesor/a-otros",
"Auxiliar",
"Auxiliar de control",
"Auxiliar-ayuda a domicilio",
"Auxiliar-jardin de infancia",
"Auxiliar-servicios sociales",
"Ayudante de marroquineria",
"Ayudante de produccion",
"Azafata",
"Azafata-azafata de vuelo",
"Biblioteca-auxiliar de biblioteca",
"Biblioteca-ayudante de biblioteca",
"Bibliotecario/a",
"Bibliotecario/a-auxiliar",
"Bibliotecario/a-diplomado/a biblioteconomia",
"Calderero-aislador",
"Camara",
"Capataz forestal",
"Carpintero/a",
"Carpintero/a de aluminio",
"Carpintero/a de armar en constr.",
"Carpintero/a de decorados",
"Carpintero/a de pvc",
"Carpintero/a ebanista artesano",
"Carpintero/a metalico",
"Carpintero/a-otros",
"Cerrajero/a",
"Chapista",
"Chapista de aluminio",
"Chapista industrial",
"Chapista-otros",
"Colocador/a",
"Colocador/a de moqueta",
"Colocador/a pavimentos ligeros",
"Colocador/a prefabric. hormigon",
"Colocador/a prefabricados (lig.)",
"Colocador/a tuberia hormigon",
"Colocador/a-otros",
"Comercio",
"Comercio-agente comercial",
"Comercio-agente de seguros",
"Comercio-agente inmobiliario",
"Comercio-asesor/a financiero/a",
"Comercio-ayudante de panaderia",
"Comercio-ayudante de pasteleria",
"Comercio-cajero/a",
"Comercio-carnicero/a",
"Comercio-charcutero/a",
"Comercio-control de calidad",
"Comercio-dependiente/a",
"Comercio-encargado/a",
"Comercio-expendedor/a",
"Comercio-frutero/a",
"Comercio-jefe/a de almacen",
"Comercio-manipulador/a de alimentos",
"Comercio-mozo/a de almacen",
"Comercio-otros",
"Comercio-pescadero/a",
"Comercio-repartidor/a a domicilio",
"Comercio-reponedor/a",
"Comercio-secretario comercial",
"Comercio-supervisor/a",
"Comercio-teleoperador/a",
"Comercio-vendedor/a",
"Comercio-vendedor/a a domicilio",
"Comercio-vendedor/a por telefono",
"Comercio-verdulero/a",
"Comercio-viajante",
"Conductor/a operario/a",
"Conductor/a operario/a-adoquin-pavimentador",
"Conductor/a operario/a-bulldozer",
"Conductor/a operario/a-camion volquete",
"Conductor/a operario/a-carretilla elevadora",
"Conductor/a operario/a-dumper",
"Conductor/a operario/a-excavadora",
"Conductor/a operario/a-extend.asfaltica",
"Conductor/a operario/a-grua en camion",
"Conductor/a operario/a-grua fija",
"Conductor/a operario/a-grua movil",
"Conductor/a operario/a-grua puente",
"Conductor/a operario/a-grúa telescópica",
"Conductor/a operario/a-grua torre",
"Conductor/a operario/a-hormigonera movil",
"Conductor/a operario/a-manitu",
"Conductor/a operario/a-maq. obras publicas",
"Conductor/a operario/a-maq.incadora pilotes",
"Conductor/a operario/a-maquin. de vias",
"Conductor/a operario/a-maquin.compactacion",
"Conductor/a operario/a-maquin.dragados",
"Conductor/a operario/a-maquin.explanacion",
"Conductor/a operario/a-maquinaria limpieza",
"Conductor/a operario/a-maquinas mov.t.",
"Conductor/a operario/a-martillo neumatico",
"Conductor/a operario/a-motoniveladora",
"Conductor/a operario/a-otros",
"Conductor/a operario/a-pala cargadora",
"Conductor/a operario/a-retroexcavadora",
"Construccion",
"Construccion-albañil",
"Construccion-albañil-remates",
"Construccion-albañil-replanteo",
"Construccion-albañil-revestidor",
"Construccion-alicatador/a",
"Construccion-aparejador/a",
"Construccion-aprendiz de construccion",
"Construccion-apuntalador/a de edificios",
"Construccion-artillero/a de la construccion",
"Construccion-auxiliar administ. obra",
"Construccion-auxiliar tecnico de obra",
"Construccion-ayudante de obra",
"Construccion-azulejero/a artesanal",
"Construccion-barrenista",
"Construccion-cantero/a artesan marmol o piedr",
"Construccion-cantero/a de construccion",
"Construccion-capataz de obra edificacion",
"Construccion-cristalero/a de edificios",
"Construccion-demoledor de edificios",
"Construccion-encargado/a de obra",
"Construccion-encargado/a de obra edif",
"Construccion-encargado/a de obras publicas",
"Construccion-escayolista",
"Construccion-oficial de primera",
"Construccion-oficial de segunda",
"Construccion-oficial de tercera",
"Construccion-otros",
"Construccion-peon de caminos",
"Construccion-peon de la construccion",
"Construccion-pizarrista",
"Consultor/a-medio ambiente",
"Coordinador/a de proyectos de desarrollo",
"Coordinador/a de formación",
"Crupier",
"Decorador/a",
"Decorador/a interiores",
"Decorador/a-adornista",
"Decorador/a-escaparatista",
"Decorador/a-otros",
"Documentalista",
"Ebanista",
"Educador/a social",
"Electricista",
"Electricista-aprendiz electricista",
"Electricista-ayudante de electricista",
"Electricista-electricista",
"Enmoquetador/a",
"Entrevistador/a-encuestador/a",
"Esteticista",
"Fontanero/a",
"Fotografo/a",
"Grabador/a de datos",
"Hosteleria",
"Hosteleria-aprendiz de cocina",
"Hosteleria-aprendiz de hostelería",
"Hosteleria-asistente/a de grupos turisticos",
"Hosteleria-ayudante/a de cocina",
"Hosteleria-barman",
"Hosteleria-camarero/a",
"Hosteleria-camarero/a de planta",
"Hosteleria-encargado/a",
"Hosteleria-jefe/a de cocina",
"Hosteleria-office",
"Hosteleria-otros",
"Hosteleria-pinche",
"Ilustrador/a",
"Industria",
"Industria-artesanos/as de la madera",
"Industria-artesanos/as de textiles",
"Industria-artesanos/as de textiles y cueros",
"Industria-control sistemas calidad",
"Industria-costureros/as",
"Industria-embaleje",
"Industria-encargado/a",
"Industria-fresador tornero",
"Industria-operario/a industrial",
"Industria-tintoreria",
"Industria-tratamiento de la leche",
"Industria-tratamiento de la leche y prod. lacteos",
"Industria-zapateria",
"Informatica",
"Informatica-analisis de sistemas",
"Informatica-bases de datos",
"Informatica-cibernetica",
"Informatica-diseñador grafico multimedia",
"Informatica-hardware",
"Informatica-internet",
"Informatica-jefe departamento tecnico",
"Informatica-lenguajes de programacion",
"Informática-modelador 3d",
"Informatica-programador/a web",
"Informatica-redes",
"Informatica-seguridad informatica",
"Informatica-sistemas operativos",
"Informatica-software",
"Informatica-teleinformatica",
"Instalador/a",
"Instalador/a aire acond y ventil",
"Instalador/a calefaccion",
"Instalador/a de antenas",
"Instalador/a electric.edificios",
"Instalador/a electricista",
"Instalador/a electricista indust",
"Instalador/a impermeabilizacion",
"Instalador/a mat.aislant.insonor",
"Instalador/a material aislante",
"Instalador/a tuberias de gas",
"Instalador/a tuberias industrial",
"Instalador/a tubos en zanjas",
"Instalador/a-otros",
"Interprete",
"Intérprete lenguaje de signos",
"Investigador/a social",
"Jardinero/a",
"Joyero/a",
"Limpiador/a",
"Limpiador/a acabados edificios",
"Limpiador/a de alcantarillas",
"Limpiador/a de fachadas",
"Limpiador/a de portales y esc.",
"Limpiador/a de ventanas",
"Limpiador/a de ventanas gran alt",
"Limpiador/a fachadas agua",
"Limpiador/a fachadas con arena",
"Limpiador/a-auxiliar de limpieza",
"Limpiador/a-barrendero/a",
"Limpiador/a-mantenedor/a piscinas",
"Limpiador/a-otros",
"Locutor/a de radio",
"Logistica",
"Logistica-aparcacoches",
"Logistica-chofer",
"Logistica-clasificador/a",
"Logistica-conductor/a",
"Logistica-conductor/a de ambulancias",
"Logistica-conductor/a de autobuses",
"Logistica-conductor/a de camion cisterna",
"Logistica-conductor/a de camiones",
"Logistica-conductor/a de gruas",
"Logistica-conductor/a de gruas y maq. pesada",
"Logistica-conductor/a de tractocamion",
"Logistica-conductor/a maquinaria",
"Logistica-mensajero/a",
"Logistica-otros trabajos de logistica",
"Logistica-peon carga y descarga",
"Logistica-repartidor/a",
"Marketing",
"Masajista",
"Mecanico/a",
"Mediador/a social",
"Medio ambiente-auxiliar forestal",
"Militar",
"Militar-militar",
"Modelo",
"Monitor/a",
"Monitor/a-aerobic",
"Monitor/a-baile",
"Monitor/a-bus escolar",
"Monitor/a-comedor",
"Monitor/a-coordinacion de actividades juveniles",
"Monitor/a-deportivo/a",
"Monitor/a-infantil",
"Monitor/a-mantenimiento",
"Monitor/a-tecnico de juventud",
"Montador/a",
"Montador/a cercados y vallas met",
"Montador/a de aislamientos",
"Montador/a de andamios",
"Montador/a de carpinteria gral.",
"Montador/a de grua",
"Montador/a de puertas automatic.",
"Montador/a de puertas blindadas",
"Montador/a de toldos",
"Montador/a en piedra escult/monu",
"Montador/a placas energia solar",
"Montador/a-ajust.maq.construcc",
"Montador/a-otros",
"Musico",
"Orientador/a laboral",
"Otros servicios",
"Panadero/a",
"Pastelero/a",
"Patronaje-profesor/a de patronaje industrial",
"Patronista",
"Patronista-diseñador/a",
"Peluquero/a",
"Peluquero/a-aprendiz peluquero/a",
"Peluquero/a-ayudante",
"Peluquero/a-canino",
"Peluquero/a-peluquero/a",
"Peon",
"Peon agricola",
"Peon forestal",
"Peon ganadero",
"Peon-otros",
"Periodismo",
"Periodismo-corrector/a de textos",
"Periodismo-redactor/a",
"Personal de mantenimiento",
"Pintor/a",
"Pocero",
"Produccion de espectaculos y audiovisuales",
"Profesor/a",
"Profesor/a- de cocina",
"Profesor/a-actividades artistico-manuales",
"Profesor/a-alemán",
"Profesor/a-clases particulares",
"Profesor/a-danza",
"Profesor/a-diplomado/a magisterio",
"Profesor/a-educacion fisica",
"Profesor/a-educador/a adultos",
"Profesor/a-educador/a especial",
"Profesor/a-educador/a infantil",
"Profesor/a-enseñanza secundaria",
"Profesor/a-enseñanza superior",
"Profesor/a-español para extrangeros",
"Profesor/a-formador/a informatica",
"Profesor/a-frances",
"Profesor/a-inglés",
"Profesor/a-monitor de futbol",
"Profesor/a-monitor de natacion",
"Profesor/a-monitor/a de tiempo libre",
"Profesor/a-musica",
"Profesor/a-tai chi",
"Profesor/a-universidad",
"Profesor/a-yoga",
"Programador/a",
"Relaciones publicas",
"Restaurador/a",
"Sanidad",
"Sanidad-ats",
"Sanidad-auxiliar de clinica",
"Sanidad-auxiliar de enfermeria",
"Sanidad-auxiliar de farmacia",
"Sanidad-auxiliar de geriatria",
"Sanidad-ayudante de estomatologia",
"Sanidad-bioquimica",
"Sanidad-celador/a",
"Sanidad-cuidado de ancianos/as",
"Sanidad-dentista",
"Sanidad-diplomado/a fisioterapia",
"Sanidad-enfermero/a",
"Sanidad-farmaceutico/a",
"Sanidad-higienista dental",
"Sanidad-laboratorios",
"Sanidad-masajista",
"Sanidad-medico",
"Sanidad-odontologo/a",
"Sanidad-opticos",
"Sanidad-otros",
"Sanidad-protesico dental",
"Sanidad-veterinarios/as",
"Seguridad",
"Seguridad-conserje",
"Seguridad-controlador/a de aparcamiento",
"Seguridad-detective",
"Seguridad-guarda",
"Seguridad-guarda de obra",
"Seguridad-guardaespaldas",
"Seguridad-guardia jurado",
"Seguridad-militar",
"Seguridad-otros",
"Seguridad-policia municipal",
"Seguridad-policia nacional",
"Seguridad-portero/a",
"Seguridad-portero/a de finca",
"Seguridad-vigilante",
"Servicio domestico-aux. serv. personal",
"Servicios domesticos",
"Servicios domesticos-ama de llaves",
"Servicios domesticos-canguro",
"Servicios domesticos-empleado/a de hogar",
"Servicios domesticos-empleado/a de hogar interna",
"Servicios domesticos-lavanderos/as",
"Servicios domesticos-lavanderos/as, planchadores/as",
"Servicios domesticos-limpieza",
"Servicios domesticos-limpieza de interior de edificios",
"Servicios domesticos-otros",
"Socorrista",
"Solador/a",
"Soldador/a",
"Taller",
"Taller-chapista",
"Taller-ensamblador/a",
"Taller-fresador/a",
"Taller-jefe/a de mantenimiento",
"Taller-jefe/a de taller",
"Taller-mecanica de automoviles",
"Taller-mecanica de maquinaria",
"Taller-montador/a",
"Taller-mozo/a",
"Taller-otros",
"Taller-tecnico/a de electronica",
"Taller-tecnico/a de telecomunicaciones",
"Taller-trabajador/a de artes graficas",
"Taquillero/a",
"Tecnico de cultura",
"Tecnico de imagen",
"Tecnico de semovientes",
"Tecnico de sonido",
"Tecnico en comercio exterior",
"Tecnico en electronica",
"Tecnico en estadistica",
"Tecnico en medio ambiente",
"Tecnico en proteccion civil",
"Tecnico en recursos humanos",
"Tecnico en salud ambiental",
"Técnico en tratamiento de aguas",
"Tecnico/a en publicidad",
"Tecnico/a en relac. publicas",
"Tecnico/a prevencion riesgos laborales",
"Terapeuta ocupacional",
"Trabajador/a de la ceramica",
"Trabajador/a industria textil",
"Trabajador/a industria textil-costurero/a",
"Trabajador/a social",
"Traductor/a",
"Tramoyista",
"Tramoyista-tramoyista",
"Turismo",
"Turismo- turismo rural",
"Turismo-agente de viajes",
"Turismo-agente de viajes",
"Turismo-diplomado/a",
"Turismo-gerente empresas turismo",
"Turismo-guia",
"Turismo-informador/a turistico/a"};
}
|
src/java/es/logongas/fpempresa/service/populate/GeneradorDatosAleatorios.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.logongas.fpempresa.service.populate;
import es.logongas.fpempresa.modelo.centro.Centro;
import es.logongas.fpempresa.modelo.centro.EstadoCentro;
import es.logongas.fpempresa.modelo.comun.Contacto;
import es.logongas.fpempresa.modelo.comun.geo.Direccion;
import es.logongas.fpempresa.modelo.comun.geo.Municipio;
import es.logongas.fpempresa.modelo.comun.geo.Provincia;
import es.logongas.fpempresa.modelo.comun.usuario.EstadoUsuario;
import es.logongas.fpempresa.modelo.comun.usuario.TipoUsuario;
import es.logongas.fpempresa.modelo.comun.usuario.Usuario;
import es.logongas.fpempresa.modelo.empresa.Empresa;
import es.logongas.ix3.core.BusinessException;
import es.logongas.ix3.dao.DataSession;
import es.logongas.ix3.dao.Filter;
import es.logongas.ix3.service.CRUDService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
/**
* Genera nombre aleatorios a partir de una lista de nombres.
*
* @author logongas
*/
public class GeneradorDatosAleatorios {
private GeneradorDatosAleatorios() {
}
static final public Usuario createUsuarioAleatorio(TipoUsuario tipoUsuario) {
Random random = new Random(System.currentTimeMillis());
String[] correos = {"gmail.com", "yahoo.com", "hotmail.com"};
Usuario usuario = new Usuario();
String ape1 = GeneradorDatosAleatorios.getApellidoPersona();
String ape2 = GeneradorDatosAleatorios.getApellidoPersona();
String nombre = GeneradorDatosAleatorios.getNombrePersona();
String email = ape1.substring(0, 3) + ape2.substring(0, 3) + nombre.substring(0, 3) + random.nextInt(9999) + "@" + GeneradorDatosAleatorios.getAleatorio(correos);
usuario.setApellidos(ape1 + " " + ape2);
usuario.setNombre(nombre);
usuario.setEmail(email.toLowerCase());
usuario.setPassword("a");
usuario.setTipoUsuario(tipoUsuario);
usuario.setEstadoUsuario(EstadoUsuario.ACEPTADO);
return usuario;
}
static final public Centro createCentroAleatorio() {
Centro centro = new Centro();
centro.setEstadoCentro(EstadoCentro.PERTENECE_A_FPEMPRESA);
centro.setNombre(GeneradorDatosAleatorios.getNombreCentroAleatorio());
centro.setDireccion(createDireccionAleatoria());
centro.setContacto(createContactoCentroAleatorio(centro));
return centro;
}
static final public Empresa createEmpresaAleatoria(Centro centro) {
String[] tiposEmpresa = {"Sociedad Anonima", "Sociedad Limitada", "Cooperativa", "Sociedad Laboral"};
Centro[] centros = {createCentroAleatorio(), null};
String nombreEmpresa = GeneradorDatosAleatorios.getNombreEmpresa() + " " + GeneradorDatosAleatorios.getApellidoPersona();
Empresa empresa = new Empresa();
empresa.setNombreComercial(nombreEmpresa);
empresa.setRazonSocial(nombreEmpresa + " " + GeneradorDatosAleatorios.getAleatorio(tiposEmpresa));
empresa.setDireccion(createDireccionAleatoria());
empresa.setContacto(createContactoEmpresaAleatorio(empresa));
empresa.setCentro(centro);
if (empresa.getCentro() != null) {
empresa.getDireccion().setMunicipio(getMunicipioAleatorio(empresa.getCentro().getDireccion().getMunicipio().getProvincia()));
}
empresa.setCif(GeneradorDatosAleatorios.getCif());
return empresa;
}
static final public Direccion createDireccionAleatoria() {
Direccion direccion = new Direccion();
direccion.setDatosDireccion(GeneradorDatosAleatorios.getDireccion());
direccion.setMunicipio(getMunicipioAleatorio());
return direccion;
}
static final public Contacto createContactoAleatorio() {
Contacto contacto = new Contacto();
contacto.setPersona(GeneradorDatosAleatorios.getNombrePersona() + " " + GeneradorDatosAleatorios.getApellidoPersona() + " " + GeneradorDatosAleatorios.getApellidoPersona());
contacto.setTelefono(GeneradorDatosAleatorios.getTelefono());
contacto.setFax(GeneradorDatosAleatorios.getTelefono());
return contacto;
}
static final public Provincia getProvinciaAleatoria() {
Random random = new Random();
int i = random.nextInt(provincias.length);
String nombre = provincias[i];
Provincia provincia = new Provincia();
provincia.setIdProvincia(i + 1);
provincia.setDescripcion(nombre);
return provincia;
}
static final public Municipio getMunicipioAleatorio() {
Random random = new Random();
int i = random.nextInt(municipios.length);
String nombre = municipios[i];
Municipio municipio = new Municipio();
municipio.setIdMunicipio(i + 1);
municipio.setDescripcion(nombre);
municipio.setProvincia(getProvinciaAleatoria());
return municipio;
}
static final public Municipio getMunicipioAleatorio(Provincia provincia) {
Municipio municipio = getMunicipioAleatorio();
municipio.setProvincia(provincia);
return municipio;
}
static final public Contacto createContactoEmpresaAleatorio(Empresa empresa) {
Contacto contacto = createContactoAleatorio();
contacto.setUrl("http://www." + empresa.getNombreComercial().replaceAll("\\s+", "").toLowerCase() + ".com");
contacto.setEmail("info@" + empresa.getNombreComercial().replaceAll("\\s+", "").toLowerCase() + ".com");
return contacto;
}
static final public Contacto createContactoCentroAleatorio(Centro centro) {
Contacto contacto = createContactoAleatorio();
contacto.setUrl("http://www." + centro.getNombre().replaceAll("\\s+", "").toLowerCase() + ".com");
contacto.setEmail("secretaria@" + centro.getNombre().replaceAll("\\s+", "").toLowerCase() + ".com");
return contacto;
}
static final public String getNombreEmpresa() {
return getAleatorio(empresas);
}
static final public String getNombrePersona() {
return getAleatorio(nombres);
}
static final public String getApellidoPersona() {
return getAleatorio(apellidos);
}
static final public String getDireccion() {
return getAleatorio(direcciones);
}
static final public String getNombrePuestoTrabajo() {
return getAleatorio(puestoTrabajo);
}
static final public String getNombreCentroAleatorio() {
String[] tiposCentro = {"IES", "CIPFP"};
String[] tiposPersona = {"Pintor", "", "", "Botanico", "Literato", "Arquitecto", "Poeta", "Escultor", "", "", "", "", "", "", ""};
return getAleatorio(tiposCentro) + " " + getAleatorio(tiposPersona) + " " + getNombrePersona() + " " + getApellidoPersona();
}
static final public String getTelefono() {
Random random = new Random();
Integer[] prefix = {9, 6};
return getAleatorio(prefix) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1);
}
static final public String getResumenPersona() {
String[] pre = {"Especializado en", "Puedo", "Me gusta", "Mi pasión es", "Mi hobby es", "Disfruto al", "Siempre he querido", "He trabajo en"};
return getAleatorio(pre) + " " + getAleatorio(verbo) + " " + getAleatorio(concepto) + " " + getAleatorio(complemento);
}
static final public String getCarreraUniversitaria() {
return getAleatorio(carreras);
}
static final public String getCif() {
Random random = new Random();
String[] letrasIniciales = {"C", "D", "F", "G", "J", "N", "P", "Q", "R", "S", "V", "W"};
String cifSinLetra = getAleatorio(letrasIniciales) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1);
return cifSinLetra + getLetraCif(cifSinLetra);
}
static final public String getNif() {
Random random = new Random();
String[] letrasIniciales = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "X"};
String nifSinLetra = getAleatorio(letrasIniciales) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1) + "" + (random.nextInt(8) + 1);
return nifSinLetra + getLetraNif(nifSinLetra);
}
private static String getLetraNif(String nifSinLetra) {
String letras = "TRWAGMYFPDXBNJZSQVHLCKE";
int valor;
if (nifSinLetra.startsWith("X")) {
//Es un NIE
valor = Integer.parseInt(nifSinLetra.substring(1, nifSinLetra.length() - 1));
} else if (nifSinLetra.startsWith("Y")) {
//Es un NIE
valor = 10000000 + Integer.parseInt(nifSinLetra.substring(1, nifSinLetra.length() - 1));
} else if (nifSinLetra.startsWith("Z")) {
//Es un NIE
valor = 20000000 + Integer.parseInt(nifSinLetra.substring(1, nifSinLetra.length() - 1));
} else {
//Es un NIF
valor = Integer.parseInt(nifSinLetra.substring(0, nifSinLetra.length() - 1));
}
return "" + letras.charAt(valor % 23);
}
private static String getLetraCif(String cifSinLetra) {
int a = 0;
a = a + Integer.parseInt(cifSinLetra.substring(2, 3));
a = a + Integer.parseInt(cifSinLetra.substring(4, 5));
a = a + Integer.parseInt(cifSinLetra.substring(6, 7));
int b = 0;
for (int i = 0; i < 4; i++) {
String parcialB = ((Integer.parseInt(cifSinLetra.substring((i * 2) + 1, (i * 2) + 2)) * 2) + "") + "0";
b = b + Integer.parseInt(parcialB.substring(0, 1)) + Integer.parseInt(parcialB.substring(1, 2));
}
int c = a + b;
String sc = ("0" + c);
int e = Integer.parseInt(sc.substring(sc.length() - 1));
int d = e;
if (e != 0) {
d = 10 - e;
}
String[] codigos = {"J", "A", "B", "C", "D", "E", "F", "G", "H", "I"};
return codigos[d];
}
static final public Date getFecha(int minAnyos, int maxAnyos) {
Random random = new Random();
Calendar calendar = new GregorianCalendar();
if (minAnyos == maxAnyos) {
calendar.add(Calendar.YEAR, -minAnyos);
} else {
calendar.add(Calendar.YEAR, -(minAnyos + random.nextInt(maxAnyos - minAnyos)));
}
calendar.add(Calendar.DATE, -random.nextInt(360));
return calendar.getTime();
}
static final public String getAleatorio(String[] datos) {
Random random = new Random();
return datos[random.nextInt(datos.length)];
}
static final public Object getAleatorio(Object[] datos) {
Random random = new Random();
return datos[random.nextInt(datos.length)];
}
static final public <T> T getAleatorio(List<T> datos) {
Random random = new Random();
return datos.get(random.nextInt(datos.size()));
}
private static final String[] municipios = {"Tobarra",
"Valdeganga",
"Vianos",
"Villa de Ves",
"Villalgordo del Júcar",
"Villamalea",
"Villapalacios",
"Villarrobledo",
"Villatoya",
"Villavaliente",
"Villaverde de Guadalimar",
"Viveros",
"Yeste",
"Pozo Cañada",
"Adsubia",
"Agost",
"Agres",
"Aigües",
"Albatera",
"Alcalalí",
"Alcocer de Planes",
"Alcoleja",
"Alcoy/Alcoi",
"Alfafara",
"Alfàs del Pi",
"Algorfa",
"Algueña",
"Alicante/Alacant",
"Almoradí",
"Almudaina",
"Alqueria",
"Altea",
"Aspe",
"Balones",
"Banyeres de Mariola",
"Benasau",
"Beneixama",
"Benejúzar"
};
private static final String[] provincias = {"Araba/Álava",
"Albacete",
"Alicante/Alacant",
"Almería",
"Ávila",
"Badajoz",
"Balears, Illes",
"Barcelona",
"Burgos",
"Cáceres",
"Cádiz",
"Castellón/Castelló",
"Ciudad Real",
"Córdoba",
"Coruña, A",
"Cuenca",
"Girona",
"Granada",
"Guadalajara",
"Gipuzkoa",
"Huelva",
"Huesca",
"Jaén",
"León",
"Lleida",
"Rioja, La",
"Lugo",
"Madrid",
"Málaga",
"Murcia",
"Navarra",
"Ourense",
"Asturias",
"Palencia",
"Palmas, Las",
"Pontevedra",
"Salamanca",
"Santa Cruz de Tenerife",
"Cantabria",
"Segovia",
"Sevilla",
"Soria",
"Tarragona",
"Teruel",
"Toledo",
"Valencia/Valéncia",
"Valladolid",
"Bizkaia",
"Zamora",
"Zaragoza",
"Ceuta",
"Melilla"};
private static final String[] direcciones = {"c/San Vicente Ferrer, 15 bajo ",
"c/ San Pedro, 12",
"c/ Luis Oliag, 69 1",
"c/ Sanchis Sivera, 18 bajo",
"Av.Naquera, 44-1",
"Crta. CV416, s/n",
"c/ Escultor Beltran 11",
"c/ Altamira, 49",
"c/ Blasco Ibañez, 192",
"c/ Enginyer Balaguer 76-2-14",
"Av. San Lorenzo, 39",
"c/ Cervantes, 3 ",
"Av. Gandia, 45",
"Escultor Aixa, 12-2",
"Urb. Los lagos 519 - Apt. Correos 69",
"c/Dos de Mayo, 92 bajo ",
"c/ Jacinto Benavent, 11",
"Av. Beato Ferreres 1-1-4 ",
"Cami del Molí 9 bajo ",
"c/ Alqueria de Soria, 40-4",
"c/ Benifairó, 1-1 ",
"c/ Sueca 25 ",
"c/ San Isidro Labrador, s/n",
"c/ Senda del Secanet 44-8",
"c/ Dr.Fleming, 30",
"Av. Real de Madrid, 20 ",
"Camino Moncada, 64-9 B ",
"c/ Bona Bista, 4 ",
"c/ Manuel Lopez Varela, 32",
"C/ Luis Vives, 18 ",
"c/ La Sangre, s/n (Edif Mcpal)",
"c/ Alberola 21",
"Carrer del Mig 18-1",
"c/ Pintor Tarrasó, 62-1 ",
"c/Virgen de Campanar 15-10ª ",
"Ronda Joan Fuster, 6 bajo",
"C/ Remedios Lizondo, 1",
"c/ Benimamet, 20",
"c/ Juan de Juanes 3 bajo",
"c/ Reyes Católicos, 38",
"carrer moreretes 1 ",
"c/ San Antonio 4",
"Pl.Españoleto 2",
"C/ San Antoni, 4-b",
"País Valencià, 17",
"Jaime de Olit, 31 ",
"C/ Mercado, 15 bajo ",
"PASSATGE REIX, 1-3-14",
"C/ Felipe Valls, 175",
"Avd. Alqueria de Roc, 12-24",
"Avd. Censals 22",
"Avd. Passeig del Oficis 28",
"Avd. Ausias March, 40",
"c/Padre Fullana, 8 ",
"c/Xátiva, 24 bajo ",
"c/Constitución, 35 bajo ",
"c/ Salvador Botella, 33 -1-1",
"Avd. La Bastida, 12",
"C/ Leonardo Bonet, 8-1-3",
"Avd. Mayor Santa Catalina, 11",
"Avd. Lluis Suñer, 28 B",
"Avd. Puchadeta del Sord, 16",
"Avda. Corts Valencianes, 26",
"P.Ind El Brosquil, c/ 11 Parc 12A",
"c/ Jubilados, 19-2",
"Virgen Dolores, 9-bajo ",
"Plaza Cabanilles, 4-2-6",
"C/ Cirene, 12 arpart. B8",
"Avd. Encarnacio 2",
"Avd. Ausias March, 28",
"Avd. Medico Marcial Bernat, 10",
"Avd. San Sebastián, 102",
"Avd. Botánico Cabanilles, 5",
"c/ La Savina, 1-D",
"c/ Senia de la Llobera, s/n Nave 1",
"c/ Hernan Cortes 3 ",
"P.Germanies, 93 Local B ",
"c/Llauri, 25 bajo ",
"c/ Dr Fleming, 57",
"C/ Vergeret, 1-4-18",
"Pais Valenciano, 36",
"c/San Rafael 74 ",
"C/ Ribera Baixa, 128",
"Menendez Pelayo, 19",
"C/ Pintor Sorolla, 5",
"c/ Vte.Andrés Estellés, 31 ",
"c/ 25 d`aBril, 11 ",
"c/ San Cristobal, 10",
"Plaça Major, 3",
"Almeria, 8 pta 6",
"c/Joaquin Sorolla 49 - 5",
"c/ Maestro Amblar, 6",
"c/ Padre Feijó, 4 Esc 1 pta 20",
"c/ Marques de Montortal, 45b",
"c/ Cumbres Mayores, 4-2 ",
"carrtera LLiria 113-4 ",
"c/ Maestro Rodrigo, 37 bajo",
"C/ Picassent 7-10",
"Av.Diputación, 1-bajo",
"Plaça del Poble 1",
"Calle Marines 2-12",
"c/Colon, 6 bajo ",
"c/ Pintor Sorolla, 12 ",
"c/ Torrent, 5-bajo",
"c/ Benemerita Guardia Civil, 19 ",
"c/ Mancomunidad Alto Turia, s/n",
"Plaza de España, 1",
"c/ San Vicente Mártir, 16 Entr 1 pta 6",
"c/ Camino de Vera s/n ",
"c/ De la Ribera, 16",
"c/ Jose Todolí Cucarella 52",
"c/ Valencia, 2",
"c/ Ermita, 36 ",
"c/ San Antonio, 42",
"c/ Antigua Via del Ferrocarril s/n",
"c/ Vicent Tomas Marti, 14-9",
"c/ Cervantes, 16-b",
"Calle Acacias, 14 ",
"Plaza La Cenia, 7 bajo ",
"c/ Padre Gil Sendra, 17 bajo",
"c/ Virgen del Socorro, 10-8",
"c/ Madre Vedruna, 15-B",
"c/ Puente, 4",
"C/ Mestre Serrano, 20",
"c/ Elionor Ripoll, 13",
"c/ Tauleta, 15",
"c/ Pinedo al Mar 27 bajo ",
"C/ Bonavista 11",
"Av. Joanot Martorel, 18",
"Pza.Músico Espí 9-5ª ",
"c/Morella, 11 Bajo A ",
"c/ Pais Valencia, 14-2º-3ª",
"Av.de Pera, 3",
"c/ Fco. Valldecabres, 2-7",
"c/ Actor Rambal, 29-1",
"c/ Lepanto, 50",
"c/ Carles Salvador 3",
"Ronda Sindic A. Albuixech, 121",
"c/ Maestro Palau, 98",
"c/ Antonio Suarez, 22-14",
"Carrera Malilla, 80 bajo",
"c/Llano de Zaidia, 17 bajo ",
"c/Abadia 20 ",
"c/ Magdalena, 87 bajo ",
"c/Caja de Ahorros, 7 ",
"c/ San Miquel 15",
"c/Almas, 19",
"c/ Parroco Miguel Tarin 30",
"c/Blasco Ibañez, 38",
"c/ Pino 8 ",
"c/Gandia, 26 ",
"c/Vicente Puchol, 16-1 ",
"c/Blasco Ibáñez, 72 bajo ",
"Avda.Dr.Waskman, 58 bajo ",
"c/ D. Enrique Olmos Cercós, 2B-2",
"c/Raquel Payá, 14 ",
"c/ Pintor Sorolla 13",
"c/ Jaume I, 36 bajo Izda",
"c/Angel, 21 ",
"Avda.Pais Valencia, 15 bajo ",
"Av Museros, 25-46",
"c/ Del Foc, 1",
"c/ Turia 21",
"c/Pinar, 5 bajo ",
"c/ Gran Via Ramon y Cajal 13 bajo",
"c/ La Tauleta, 36",
"c/ Libertad, 10",
"c/Buen Suceso, 3-6ª ",
"c/ Arzobispo Olaechea, 39 B",
"c/ Rio Genil, 4-11 ",
"c/ Jaume I, 17 ",
"c/ Dr. Fleming, 7-1",
"Plaza Antonio Machado 8",
"Plaza Las Escuelas, 22-3",
"Plaza San Cayetano, 10-12",
"Avd. Cid, 3-3-9",
"Plaza Favara, 4",
"Plaza Luz Casanova, 11-bajo C",
"Plaza Alcalde Miguel Domingo, 3",
"Plaza Gandia, 21",
"Plaza Mar, 17",
"Pza Don Manuel Garcia Izquierdo, S/",
"Avda Del Sur 22 - 3 - 5",
"c/ José Iturbi, 27-B",
"Plaza Coronel Lopez Aparicio 4"};
private static final String[] empresas = {"kubs",
"mirecker",
"anahi",
"appeph",
"sanle",
"intioga",
"hebar",
"hudon",
"walsk",
"medinp",
"wiresta",
"pfiensol",
"bree",
"banciter",
"iton",
"stan",
"watics",
"pohorp",
"capuscona",
"beling",
"quervarix",
"coman",
"fraltalko",
"brius",
"yamatho",
"valpopars",
"catita",
"branatin",
"natic",
"wespen",
"eves",
"abeng",
"teles",
"bankyo",
"grum",
"tsung",
"amenom",
"serne",
"aluxon",
"sheles",
"angost",
"yoki",
"mizai",
"happgno",
"vivers",
"daita",
"danz",
"authan",
"scommurow",
"tectohn",
"teill",
"frants",
"costpatsu",
"badide",
"reldancon",
"bhans",
"urbaisl",
"pacitsch",
"carti",
"symars",
"shorts",
"irie",
"meran",
"medic",
"dare",
"negank",
"hinos",
"cumb",
"ahon",
"nagan",
"facom",
"wace",
"sindskair",
"worizern",
"sumin",
"hancianey",
"poling",
"urbalern",
"moubillo",
"aurkersto",
"hyds",
"eures",
"nidtral",
"amber",
"haria",
"cumins",
"ecommit",
"alpos",
"cond",
"capir",
"assai",
"synt",
"avin",
"holay",
"glar",
"hewirles",
"ters",
"parminer",
"nage",
"kellima"};
private static final String[] nombres = {"Antonio",
"Jose",
"Manuel",
"Francisco",
"Juan",
"David",
"Jose Antonio",
"Jose Luis",
"Javier",
"Francisco Javier",
"Jesus",
"Daniel",
"Carlos",
"Miguel",
"Alejandro",
"Jose Manuel",
"Rafael",
"Pedro",
"Angel",
"Miguel Angel",
"Jose Maria",
"Fernando",
"Pablo",
"Luis",
"Sergio",
"Jorge",
"Alberto",
"Juan Carlos",
"Juan Jose",
"Alvaro",
"Diego",
"Adrian",
"Juan Antonio",
"Raul",
"Enrique",
"Ramon",
"Vicente",
"Ivan",
"Ruben",
"Oscar",
"Andres",
"Joaquin",
"Juan Manuel",
"Santiago",
"Eduardo",
"Victor",
"Roberto",
"Jaime",
"Francisco Jose",
"Mario",
"Ignacio",
"Alfonso",
"Salvador",
"Ricardo",
"Marcos",
"Jordi",
"Emilio",
"Julian",
"Julio",
"Guillermo",
"Gabriel",
"Tomas",
"Agustin",
"Jose Miguel",
"Marc",
"Gonzalo",
"Felix",
"Jose Ramon",
"Mohamed",
"Hugo",
"Joan",
"Ismael",
"Nicolas",
"Cristian",
"Samuel",
"Mariano",
"Josep",
"Domingo",
"Juan Francisco",
"Aitor",
"Martin",
"Alfredo",
"Sebastian",
"Jose Carlos",
"Felipe",
"Hector",
"Cesar",
"Jose Angel",
"Jose Ignacio",
"Victor Manuel",
"Iker",
"Gregorio",
"Luis Miguel",
"Alex",
"Jose Francisco",
"Juan Luis",
"Rodrigo",
"Albert",
"Xavier",
"Lorenzo",
"Maria Carmen",
"Maria",
"Carmen",
"Josefa",
"Isabel",
"Ana maria",
"Maria Pilar",
"Maria Dolores",
"Maria Teresa",
"Ana",
"Laura",
"Francisca",
"Maria Angeles",
"Cristina",
"Antonia",
"Marta",
"Dolores",
"Maria Isabel",
"Maria Jose",
"Lucia",
"Maria Luisa",
"Pilar",
"Elena",
"Concepcion",
"Sara",
"Paula",
"Manuela",
"Mercedes",
"Rosa Maria",
"Raquel",
"Maria Jesus",
"Juana",
"Rosario",
"Teresa",
"Encarnacion",
"Beatriz",
"Nuria",
"Silvia",
"Julia",
"Rosa",
"Montserrat",
"Patricia",
"Irene",
"Andrea",
"Rocio",
"Monica",
"Alba",
"Maria mar",
"Angela",
"Sonia",
"Alicia",
"Sandra",
"Susana",
"Margarita",
"Marina",
"Yolanda",
"Maria Josefa",
"Natalia",
"Maria Rosario",
"Inmaculada",
"Eva",
"Maria Mercedes",
"Esther",
"Ana isabel",
"Angeles",
"Noelia",
"Claudia",
"Veronica",
"Amparo",
"Maria rosa",
"Carolina",
"Maria Victoria",
"Carla",
"Eva maria",
"Maria Concepcion",
"Nerea",
"Lorena",
"Ana Belen",
"Victoria",
"Miriam",
"Maria Elena",
"Sofia",
"Catalina",
"Ines",
"Maria Antonia",
"Consuelo",
"Emilia",
"Maria Nieves",
"Lidia",
"Luisa",
"Gloria",
"Celia",
"Olga",
"Aurora",
"Esperanza",
"Josefina",
"Maria soledad",
"Milagros",
"Maria cristina",
"Daniela"};
private static final String[] apellidos = {"Garcia",
"Gonzalez",
"Rodriguez",
"Fernandez",
"Lopez",
"Martinez",
"Sanchez",
"Perez",
"Gomez",
"Martin",
"Jimenez",
"Ruiz",
"Hernandez",
"Diaz",
"Moreno",
"Alvarez",
"Romero",
"Alonso",
"Gutierrez",
"Navarro",
"Torres",
"Dominguez",
"Vazquez",
"Ramos",
"Gil",
"Ramirez",
"Serrano",
"Blanco",
"Molina",
"Suarez",
"Morales",
"Ortega",
"Delgado",
"Castro",
"Ortiz",
"Rubio",
"Marin",
"Sanz",
"Iglesias",
"Medina",
"Garrido",
"Cortes",
"Santos",
"Castillo",
"Lozano",
"Guerrero",
"Cano",
"Prieto",
"Mendez",
"Calvo",
"Cruz",
"Gallego",
"Vidal",
"Leon",
"Marquez",
"Herrera",
"Flores",
"Cabrera",
"Campos",
"Vega",
"Fuentes",
"Diez",
"Carrasco",
"Caballero",
"Nieto",
"Reyes",
"Aguilar",
"Pascual",
"Herrero",
"Santana",
"Lorenzo",
"Hidalgo",
"Montero",
"Gimenez",
"Ferrer",
"Duran",
"Santiago",
"Vicente",
"Benitez",
"Mora",
"Arias",
"Vargas",
"Carmona",
"Crespo",
"Roman",
"Pastor",
"Soto",
"Saez",
"Velasco",
"Moya",
"Soler",
"Esteban",
"Parra",
"Bravo",
"Gallardo",
"Rojas"};
private static final String[] verbo = {"acelerar",
"acoplar",
"adoptar",
"agregar",
"alimentar",
"articular",
"analizar",
"complementar",
"cultivar",
"conceptualizar",
"compatibilizar",
"contextualizar",
"construir",
"desarrollar",
"desplegar",
"diseñar",
"encapsular",
"engranar",
"ensamblar",
"escalar",
"estimular",
"evaluar",
"evolucionar",
"explotar",
"extender",
"facilitar",
"favorecer",
"generar",
"gestionar",
"habilitar",
"incubar",
"implementar",
"impulsar",
"incentivar",
"integrar",
"maximizar",
"nivelar",
"reconvertir",
"re-inventar",
"reformatear",
"objetivizar",
"optimizar",
"orquestar",
"propulsar",
"racionalizar",
"sinergizar",
"sintetizar",
"sistematizar",
"transformar",
"visualizar"};
private static final String[] concepto = {"actuaciones",
"ajustes",
"aplicaciones",
"asociaciones",
"arquitecturas",
"infraestructuras",
"iniciativas",
"canales",
"comunidades",
"conectividades",
"contenidos",
"convergencias",
"dinámicas",
"esquemas",
"estructuras",
"experiencias",
"funcionalidades",
"interfaces",
"mecanismos",
"mercados",
"metodologías",
"modelos",
"nichos",
"indicadores",
"paradigmas",
"plataformas",
"políticas",
"portales",
"protocolos",
"proyecciones",
"proyectos",
"redes",
"relaciones",
"servicios electrónicos",
"sinergias",
"sistemas",
"soluciones",
"tendencias",
"tecnologías",
"topologías",
"transiciones",
"transposiciones",
"usuarios"};
private static final String[] complemento = {"de activación",
"afines",
"de banda ancha",
"business-to-business",
"business-to-consumer",
"conceptuales",
"con capacidades dinámicas",
"con capacidades Web",
"de código abierto",
"de colaboración",
"de contorno",
"de convergencia",
"de distribución",
"escalables",
"eficientes",
"globales",
"granulares",
"de iniciativa",
"llave en mano",
"a medida",
"modulares",
"con interactividad",
"one-to-one",
"perimetrales",
"de personalización",
"de tipo plug-and-play",
"punto-com",
"con proactividad",
"de re-ingeniería",
"de re-posicionamiento",
"del sector privado",
"de atención al cliente",
"de tecnología punta",
"en tiempo real",
"de redes sociales",
"sostenibles",
"de la web 2.0",
"transparentes",
"de transición",
"de última generación",
"con centro en el usuario",
"de valor añadido",
"verticales",
"de visión periférica",
"virales",
"virtuales"};
private final static String[] carreras = {"Arqueología",
"Artes Escénicas",
"Bellas Artes",
"Conservación - Restauración de Bienes Culturales",
"Danza",
"Diseño",
"Estudios Literarios",
"Filosofía",
"Fotografía",
"Geografía",
"Astronomía y Astrofísica",
"Biología",
"Bioquímica",
"Biotecnología",
"Ciencia y Tecnología de los Alimentos",
"Ciencias Ambientales",
"Ciencias Biomédicas",
"Ciencias del Mar",
"Ciencias Experimentales",
"Enología",
"Ciencias Biomédicas",
"Ciencias de la Actividad Física y del Deporte",
"Enfermería",
"Farmacia",
"Fisioterapia",
"Logopedia",
"Medicina",
"Nutrición Humana y Dietética",
"Odontología",
"Óptica y Optometría",
"Administración y Dirección de Empresas",
"Antropología",
"Asistencia en Dirección",
"Ciencias del Trabajo y Recursos Humanos",
"Ciencias del Transporte y la Logística",
"Ciencias Políticas y de la Administración Pública",
"Comercio",
"Comunicación Audiovisual",
"Contabilidad y Finanzas",
"Criminología",
"Arquitectura",
"Diseño y Desarrollo de videojuegos",
"Ingeniería Aeroespacial",
"Ingeniería Agroambiental",
"Ingeniería Alimentaria",
"Ingeniería Ambiental",
"Ingeniería Biomédica",
"Ingeniería de Caminos, Canales y Puertos",
"Ingeniería de la Edificación",
"Ingeniería de la Energía"};
private static final String[] puestoTrabajo = {"Acomodador/a",
"Acomodador/a-acomodador/a",
"Actor/actriz",
"Administracion-atencion al cliente",
"Administracion-auxiliar administrativo/a",
"Administracion-auxiliar contable",
"Administracion-becaria asuntos sociales",
"Administracion-botones",
"Administracion-codificador de datos",
"Administracion-direccion y gestion empresarial",
"Administracion-oficial administrativo/a",
"Administracion-ordenanza",
"Administracion-otro personal de oficina",
"Administracion-otros",
"Administracion-profesional de contabilidad",
"Administracion-recepcionista",
"Administracion-secretariado",
"Agente censal",
"Agente de igualdad",
"Agente desarrollo local",
"Agente forestal",
"Agente forestal-agente forestal",
"Agente forestal-viverista",
"Agente judicial",
"Agricultor/a",
"Alfarero/a",
"Animador/a sociocultural",
"Apicultor/a",
"Archivero/a",
"Archivero/a-archivero/a",
"Archivero/a-auxiliar de archivo",
"Archivero/a-ayudante de archivo",
"Artesano/a",
"Asesor",
"Asesor de imagen",
"Asesor en prl",
"Asesor fiscal y tributario",
"Asesor juridico",
"Asesor/a-otros",
"Auxiliar",
"Auxiliar de control",
"Auxiliar-ayuda a domicilio",
"Auxiliar-jardin de infancia",
"Auxiliar-servicios sociales",
"Ayudante de marroquineria",
"Ayudante de produccion",
"Azafata",
"Azafata-azafata de vuelo",
"Biblioteca-auxiliar de biblioteca",
"Biblioteca-ayudante de biblioteca",
"Bibliotecario/a",
"Bibliotecario/a-auxiliar",
"Bibliotecario/a-diplomado/a biblioteconomia",
"Calderero-aislador",
"Camara",
"Capataz forestal",
"Carpintero/a",
"Carpintero/a de aluminio",
"Carpintero/a de armar en constr.",
"Carpintero/a de decorados",
"Carpintero/a de pvc",
"Carpintero/a ebanista artesano",
"Carpintero/a metalico",
"Carpintero/a-otros",
"Cerrajero/a",
"Chapista",
"Chapista de aluminio",
"Chapista industrial",
"Chapista-otros",
"Colocador/a",
"Colocador/a de moqueta",
"Colocador/a pavimentos ligeros",
"Colocador/a prefabric. hormigon",
"Colocador/a prefabricados (lig.)",
"Colocador/a tuberia hormigon",
"Colocador/a-otros",
"Comercio",
"Comercio-agente comercial",
"Comercio-agente de seguros",
"Comercio-agente inmobiliario",
"Comercio-asesor/a financiero/a",
"Comercio-ayudante de panaderia",
"Comercio-ayudante de pasteleria",
"Comercio-cajero/a",
"Comercio-carnicero/a",
"Comercio-charcutero/a",
"Comercio-control de calidad",
"Comercio-dependiente/a",
"Comercio-encargado/a",
"Comercio-expendedor/a",
"Comercio-frutero/a",
"Comercio-jefe/a de almacen",
"Comercio-manipulador/a de alimentos",
"Comercio-mozo/a de almacen",
"Comercio-otros",
"Comercio-pescadero/a",
"Comercio-repartidor/a a domicilio",
"Comercio-reponedor/a",
"Comercio-secretario comercial",
"Comercio-supervisor/a",
"Comercio-teleoperador/a",
"Comercio-vendedor/a",
"Comercio-vendedor/a a domicilio",
"Comercio-vendedor/a por telefono",
"Comercio-verdulero/a",
"Comercio-viajante",
"Conductor/a operario/a",
"Conductor/a operario/a-adoquin-pavimentador",
"Conductor/a operario/a-bulldozer",
"Conductor/a operario/a-camion volquete",
"Conductor/a operario/a-carretilla elevadora",
"Conductor/a operario/a-dumper",
"Conductor/a operario/a-excavadora",
"Conductor/a operario/a-extend.asfaltica",
"Conductor/a operario/a-grua en camion",
"Conductor/a operario/a-grua fija",
"Conductor/a operario/a-grua movil",
"Conductor/a operario/a-grua puente",
"Conductor/a operario/a-grúa telescópica",
"Conductor/a operario/a-grua torre",
"Conductor/a operario/a-hormigonera movil",
"Conductor/a operario/a-manitu",
"Conductor/a operario/a-maq. obras publicas",
"Conductor/a operario/a-maq.incadora pilotes",
"Conductor/a operario/a-maquin. de vias",
"Conductor/a operario/a-maquin.compactacion",
"Conductor/a operario/a-maquin.dragados",
"Conductor/a operario/a-maquin.explanacion",
"Conductor/a operario/a-maquinaria limpieza",
"Conductor/a operario/a-maquinas mov.t.",
"Conductor/a operario/a-martillo neumatico",
"Conductor/a operario/a-motoniveladora",
"Conductor/a operario/a-otros",
"Conductor/a operario/a-pala cargadora",
"Conductor/a operario/a-retroexcavadora",
"Construccion",
"Construccion-albañil",
"Construccion-albañil-remates",
"Construccion-albañil-replanteo",
"Construccion-albañil-revestidor",
"Construccion-alicatador/a",
"Construccion-aparejador/a",
"Construccion-aprendiz de construccion",
"Construccion-apuntalador/a de edificios",
"Construccion-artillero/a de la construccion",
"Construccion-auxiliar administ. obra",
"Construccion-auxiliar tecnico de obra",
"Construccion-ayudante de obra",
"Construccion-azulejero/a artesanal",
"Construccion-barrenista",
"Construccion-cantero/a artesan marmol o piedr",
"Construccion-cantero/a de construccion",
"Construccion-capataz de obra edificacion",
"Construccion-cristalero/a de edificios",
"Construccion-demoledor de edificios",
"Construccion-encargado/a de obra",
"Construccion-encargado/a de obra edif",
"Construccion-encargado/a de obras publicas",
"Construccion-escayolista",
"Construccion-oficial de primera",
"Construccion-oficial de segunda",
"Construccion-oficial de tercera",
"Construccion-otros",
"Construccion-peon de caminos",
"Construccion-peon de la construccion",
"Construccion-pizarrista",
"Consultor/a-medio ambiente",
"Coordinador/a de proyectos de desarrollo",
"Coordinador/a de formación",
"Crupier",
"Decorador/a",
"Decorador/a interiores",
"Decorador/a-adornista",
"Decorador/a-escaparatista",
"Decorador/a-otros",
"Documentalista",
"Ebanista",
"Educador/a social",
"Electricista",
"Electricista-aprendiz electricista",
"Electricista-ayudante de electricista",
"Electricista-electricista",
"Enmoquetador/a",
"Entrevistador/a-encuestador/a",
"Esteticista",
"Fontanero/a",
"Fotografo/a",
"Grabador/a de datos",
"Hosteleria",
"Hosteleria-aprendiz de cocina",
"Hosteleria-aprendiz de hostelería",
"Hosteleria-asistente/a de grupos turisticos",
"Hosteleria-ayudante/a de cocina",
"Hosteleria-barman",
"Hosteleria-camarero/a",
"Hosteleria-camarero/a de planta",
"Hosteleria-encargado/a",
"Hosteleria-jefe/a de cocina",
"Hosteleria-office",
"Hosteleria-otros",
"Hosteleria-pinche",
"Ilustrador/a",
"Industria",
"Industria-artesanos/as de la madera",
"Industria-artesanos/as de textiles",
"Industria-artesanos/as de textiles y cueros",
"Industria-control sistemas calidad",
"Industria-costureros/as",
"Industria-embaleje",
"Industria-encargado/a",
"Industria-fresador tornero",
"Industria-operario/a industrial",
"Industria-tintoreria",
"Industria-tratamiento de la leche",
"Industria-tratamiento de la leche y prod. lacteos",
"Industria-zapateria",
"Informatica",
"Informatica-analisis de sistemas",
"Informatica-bases de datos",
"Informatica-cibernetica",
"Informatica-diseñador grafico multimedia",
"Informatica-hardware",
"Informatica-internet",
"Informatica-jefe departamento tecnico",
"Informatica-lenguajes de programacion",
"Informática-modelador 3d",
"Informatica-programador/a web",
"Informatica-redes",
"Informatica-seguridad informatica",
"Informatica-sistemas operativos",
"Informatica-software",
"Informatica-teleinformatica",
"Instalador/a",
"Instalador/a aire acond y ventil",
"Instalador/a calefaccion",
"Instalador/a de antenas",
"Instalador/a electric.edificios",
"Instalador/a electricista",
"Instalador/a electricista indust",
"Instalador/a impermeabilizacion",
"Instalador/a mat.aislant.insonor",
"Instalador/a material aislante",
"Instalador/a tuberias de gas",
"Instalador/a tuberias industrial",
"Instalador/a tubos en zanjas",
"Instalador/a-otros",
"Interprete",
"Intérprete lenguaje de signos",
"Investigador/a social",
"Jardinero/a",
"Joyero/a",
"Limpiador/a",
"Limpiador/a acabados edificios",
"Limpiador/a de alcantarillas",
"Limpiador/a de fachadas",
"Limpiador/a de portales y esc.",
"Limpiador/a de ventanas",
"Limpiador/a de ventanas gran alt",
"Limpiador/a fachadas agua",
"Limpiador/a fachadas con arena",
"Limpiador/a-auxiliar de limpieza",
"Limpiador/a-barrendero/a",
"Limpiador/a-mantenedor/a piscinas",
"Limpiador/a-otros",
"Locutor/a de radio",
"Logistica",
"Logistica-aparcacoches",
"Logistica-chofer",
"Logistica-clasificador/a",
"Logistica-conductor/a",
"Logistica-conductor/a de ambulancias",
"Logistica-conductor/a de autobuses",
"Logistica-conductor/a de camion cisterna",
"Logistica-conductor/a de camiones",
"Logistica-conductor/a de gruas",
"Logistica-conductor/a de gruas y maq. pesada",
"Logistica-conductor/a de tractocamion",
"Logistica-conductor/a maquinaria",
"Logistica-mensajero/a",
"Logistica-otros trabajos de logistica",
"Logistica-peon carga y descarga",
"Logistica-repartidor/a",
"Marketing",
"Masajista",
"Mecanico/a",
"Mediador/a social",
"Medio ambiente-auxiliar forestal",
"Militar",
"Militar-militar",
"Modelo",
"Monitor/a",
"Monitor/a-aerobic",
"Monitor/a-baile",
"Monitor/a-bus escolar",
"Monitor/a-comedor",
"Monitor/a-coordinacion de actividades juveniles",
"Monitor/a-deportivo/a",
"Monitor/a-infantil",
"Monitor/a-mantenimiento",
"Monitor/a-tecnico de juventud",
"Montador/a",
"Montador/a cercados y vallas met",
"Montador/a de aislamientos",
"Montador/a de andamios",
"Montador/a de carpinteria gral.",
"Montador/a de grua",
"Montador/a de puertas automatic.",
"Montador/a de puertas blindadas",
"Montador/a de toldos",
"Montador/a en piedra escult/monu",
"Montador/a placas energia solar",
"Montador/a-ajust.maq.construcc",
"Montador/a-otros",
"Musico",
"Orientador/a laboral",
"Otros servicios",
"Panadero/a",
"Pastelero/a",
"Patronaje-profesor/a de patronaje industrial",
"Patronista",
"Patronista-diseñador/a",
"Peluquero/a",
"Peluquero/a-aprendiz peluquero/a",
"Peluquero/a-ayudante",
"Peluquero/a-canino",
"Peluquero/a-peluquero/a",
"Peon",
"Peon agricola",
"Peon forestal",
"Peon ganadero",
"Peon-otros",
"Periodismo",
"Periodismo-corrector/a de textos",
"Periodismo-redactor/a",
"Personal de mantenimiento",
"Pintor/a",
"Pocero",
"Produccion de espectaculos y audiovisuales",
"Profesor/a",
"Profesor/a- de cocina",
"Profesor/a-actividades artistico-manuales",
"Profesor/a-alemán",
"Profesor/a-clases particulares",
"Profesor/a-danza",
"Profesor/a-diplomado/a magisterio",
"Profesor/a-educacion fisica",
"Profesor/a-educador/a adultos",
"Profesor/a-educador/a especial",
"Profesor/a-educador/a infantil",
"Profesor/a-enseñanza secundaria",
"Profesor/a-enseñanza superior",
"Profesor/a-español para extrangeros",
"Profesor/a-formador/a informatica",
"Profesor/a-frances",
"Profesor/a-inglés",
"Profesor/a-monitor de futbol",
"Profesor/a-monitor de natacion",
"Profesor/a-monitor/a de tiempo libre",
"Profesor/a-musica",
"Profesor/a-tai chi",
"Profesor/a-universidad",
"Profesor/a-yoga",
"Programador/a",
"Relaciones publicas",
"Restaurador/a",
"Sanidad",
"Sanidad-ats",
"Sanidad-auxiliar de clinica",
"Sanidad-auxiliar de enfermeria",
"Sanidad-auxiliar de farmacia",
"Sanidad-auxiliar de geriatria",
"Sanidad-ayudante de estomatologia",
"Sanidad-bioquimica",
"Sanidad-celador/a",
"Sanidad-cuidado de ancianos/as",
"Sanidad-dentista",
"Sanidad-diplomado/a fisioterapia",
"Sanidad-enfermero/a",
"Sanidad-farmaceutico/a",
"Sanidad-higienista dental",
"Sanidad-laboratorios",
"Sanidad-masajista",
"Sanidad-medico",
"Sanidad-odontologo/a",
"Sanidad-opticos",
"Sanidad-otros",
"Sanidad-protesico dental",
"Sanidad-veterinarios/as",
"Seguridad",
"Seguridad-conserje",
"Seguridad-controlador/a de aparcamiento",
"Seguridad-detective",
"Seguridad-guarda",
"Seguridad-guarda de obra",
"Seguridad-guardaespaldas",
"Seguridad-guardia jurado",
"Seguridad-militar",
"Seguridad-otros",
"Seguridad-policia municipal",
"Seguridad-policia nacional",
"Seguridad-portero/a",
"Seguridad-portero/a de finca",
"Seguridad-vigilante",
"Servicio domestico-aux. serv. personal",
"Servicios domesticos",
"Servicios domesticos-ama de llaves",
"Servicios domesticos-canguro",
"Servicios domesticos-empleado/a de hogar",
"Servicios domesticos-empleado/a de hogar interna",
"Servicios domesticos-lavanderos/as",
"Servicios domesticos-lavanderos/as, planchadores/as",
"Servicios domesticos-limpieza",
"Servicios domesticos-limpieza de interior de edificios",
"Servicios domesticos-otros",
"Socorrista",
"Solador/a",
"Soldador/a",
"Taller",
"Taller-chapista",
"Taller-ensamblador/a",
"Taller-fresador/a",
"Taller-jefe/a de mantenimiento",
"Taller-jefe/a de taller",
"Taller-mecanica de automoviles",
"Taller-mecanica de maquinaria",
"Taller-montador/a",
"Taller-mozo/a",
"Taller-otros",
"Taller-tecnico/a de electronica",
"Taller-tecnico/a de telecomunicaciones",
"Taller-trabajador/a de artes graficas",
"Taquillero/a",
"Tecnico de cultura",
"Tecnico de imagen",
"Tecnico de semovientes",
"Tecnico de sonido",
"Tecnico en comercio exterior",
"Tecnico en electronica",
"Tecnico en estadistica",
"Tecnico en medio ambiente",
"Tecnico en proteccion civil",
"Tecnico en recursos humanos",
"Tecnico en salud ambiental",
"Técnico en tratamiento de aguas",
"Tecnico/a en publicidad",
"Tecnico/a en relac. publicas",
"Tecnico/a prevencion riesgos laborales",
"Terapeuta ocupacional",
"Trabajador/a de la ceramica",
"Trabajador/a industria textil",
"Trabajador/a industria textil-costurero/a",
"Trabajador/a social",
"Traductor/a",
"Tramoyista",
"Tramoyista-tramoyista",
"Turismo",
"Turismo- turismo rural",
"Turismo-agente de viajes",
"Turismo-agente de viajes",
"Turismo-diplomado/a",
"Turismo-gerente empresas turismo",
"Turismo-guia",
"Turismo-informador/a turistico/a"};
}
|
feat(populate):Nuevos métodos de crear objetos rellenos del modelo
|
src/java/es/logongas/fpempresa/service/populate/GeneradorDatosAleatorios.java
|
feat(populate):Nuevos métodos de crear objetos rellenos del modelo
|
<ide><path>rc/java/es/logongas/fpempresa/service/populate/GeneradorDatosAleatorios.java
<ide> import es.logongas.fpempresa.modelo.comun.usuario.EstadoUsuario;
<ide> import es.logongas.fpempresa.modelo.comun.usuario.TipoUsuario;
<ide> import es.logongas.fpempresa.modelo.comun.usuario.Usuario;
<add>import es.logongas.fpempresa.modelo.educacion.Ciclo;
<ide> import es.logongas.fpempresa.modelo.empresa.Empresa;
<del>import es.logongas.ix3.core.BusinessException;
<del>import es.logongas.ix3.dao.DataSession;
<del>import es.logongas.ix3.dao.Filter;
<del>import es.logongas.ix3.service.CRUDService;
<del>import java.util.ArrayList;
<add>import es.logongas.fpempresa.modelo.titulado.ExperienciaLaboral;
<add>import es.logongas.fpempresa.modelo.titulado.FormacionAcademica;
<add>import es.logongas.fpempresa.modelo.titulado.Idioma;
<add>import es.logongas.fpempresa.modelo.titulado.NivelIdioma;
<add>import es.logongas.fpempresa.modelo.titulado.TipoDocumento;
<add>import es.logongas.fpempresa.modelo.titulado.TipoFormacionAcademica;
<add>import es.logongas.fpempresa.modelo.titulado.Titulado;
<add>import es.logongas.fpempresa.modelo.titulado.TituloIdioma;
<ide> import java.util.Calendar;
<ide> import java.util.Date;
<ide> import java.util.GregorianCalendar;
<ide>
<ide> static final public Empresa createEmpresaAleatoria(Centro centro) {
<ide> String[] tiposEmpresa = {"Sociedad Anonima", "Sociedad Limitada", "Cooperativa", "Sociedad Laboral"};
<del> Centro[] centros = {createCentroAleatorio(), null};
<ide>
<ide> String nombreEmpresa = GeneradorDatosAleatorios.getNombreEmpresa() + " " + GeneradorDatosAleatorios.getApellidoPersona();
<ide> Empresa empresa = new Empresa();
<ide> empresa.setNombreComercial(nombreEmpresa);
<ide> empresa.setRazonSocial(nombreEmpresa + " " + GeneradorDatosAleatorios.getAleatorio(tiposEmpresa));
<ide> empresa.setDireccion(createDireccionAleatoria());
<add> if (centro!=null) {
<add> empresa.getDireccion().setMunicipio(centro.getDireccion().getMunicipio());
<add> }
<ide> empresa.setContacto(createContactoEmpresaAleatorio(empresa));
<ide> empresa.setCentro(centro);
<ide>
<del> if (empresa.getCentro() != null) {
<del> empresa.getDireccion().setMunicipio(getMunicipioAleatorio(empresa.getCentro().getDireccion().getMunicipio().getProvincia()));
<del> }
<del>
<ide> empresa.setCif(GeneradorDatosAleatorios.getCif());
<ide>
<ide> return empresa;
<ide> }
<ide>
<add> static final public Titulado createTituladoAleatorio() {
<add> Titulado titulado = new Titulado();
<add> String[] permisosConducir = {"A", "A", "B", "B", "C1", "C", null, null, null, null, null, null, null, null, null, null, null, null, null, null};
<add>
<add> titulado.setDireccion(createDireccionAleatoria());
<add> titulado.setFechaNacimiento(GeneradorDatosAleatorios.getFecha(18, 35));
<add> titulado.setTipoDocumento(TipoDocumento.NIF_NIE);
<add> titulado.setNumeroDocumento(GeneradorDatosAleatorios.getNif());
<add> titulado.setPermisosConducir(GeneradorDatosAleatorios.getAleatorio(permisosConducir));
<add> titulado.setTelefono(GeneradorDatosAleatorios.getTelefono());
<add> titulado.setTelefonoAlternativo(GeneradorDatosAleatorios.getTelefono());
<add> titulado.setResumen(GeneradorDatosAleatorios.getResumenPersona());
<add>
<add> return titulado;
<add> }
<add>
<ide> static final public Direccion createDireccionAleatoria() {
<ide> Direccion direccion = new Direccion();
<ide> direccion.setDatosDireccion(GeneradorDatosAleatorios.getDireccion());
<ide> return contacto;
<ide> }
<ide>
<add> static final public TituloIdioma createTituloIdiomaAleatorio(Titulado titulado) {
<add> TituloIdioma tituloIdioma =new TituloIdioma();
<add> String[] otroIdioma = {"Chino", "Ruso", "Armenio", "Italiano", "Árabe", "Griego", "Japonés"};
<add>
<add> tituloIdioma.setTitulado(titulado);
<add> tituloIdioma.setFecha(GeneradorDatosAleatorios.getFecha(0, 5));
<add> tituloIdioma.setIdioma((Idioma) GeneradorDatosAleatorios.getAleatorio(Idioma.values()));
<add> if (tituloIdioma.getIdioma() == Idioma.OTRO) {
<add> tituloIdioma.setOtroIdioma(GeneradorDatosAleatorios.getAleatorio(otroIdioma));
<add> }
<add> tituloIdioma.setNivelIdioma((NivelIdioma) GeneradorDatosAleatorios.getAleatorio(NivelIdioma.values()));
<add>
<add> return tituloIdioma;
<add> }
<add>
<add>
<add> static final public FormacionAcademica createFormacionAcademicaAleatoria(Titulado titulado) {
<add> FormacionAcademica formacionAcademica = new FormacionAcademica();
<add> TipoFormacionAcademica[] tipoFormacionAcademica = {TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.CICLO_FORMATIVO, TipoFormacionAcademica.TITULO_UNIVERSITARIO};
<add> Boolean[] nuevoCentro = {false, false, false, false, false, false, true};
<add>
<add> formacionAcademica.setTitulado(titulado);
<add> formacionAcademica.setTipoFormacionAcademica((TipoFormacionAcademica) GeneradorDatosAleatorios.getAleatorio(tipoFormacionAcademica));
<add> formacionAcademica.setFecha(GeneradorDatosAleatorios.getFecha(0, 5));
<add> switch (formacionAcademica.getTipoFormacionAcademica()) {
<add> case CICLO_FORMATIVO:
<add> Ciclo ciclo=new Ciclo();
<add> ciclo.setIdCiclo(10);
<add>
<add> formacionAcademica.setCiclo(ciclo);
<add>
<add> Centro centro=new Centro();
<add> centro.setIdCentro(-1);
<add> formacionAcademica.setCentro(centro);
<add> formacionAcademica.setOtroCentro(GeneradorDatosAleatorios.getNombreCentroAleatorio());
<add>
<add>
<add> break;
<add> case TITULO_UNIVERSITARIO:
<add> formacionAcademica.setOtroCentro("Universidad de " + getProvinciaAleatoria().getDescripcion());
<add> formacionAcademica.setOtroTitulo(GeneradorDatosAleatorios.getCarreraUniversitaria());
<add> break;
<add> default:
<add> throw new RuntimeException("Tipo de formacion academicas no soportado:" + formacionAcademica.getTipoFormacionAcademica());
<add> }
<add>
<add> return formacionAcademica;
<add> }
<add>
<add> static final public ExperienciaLaboral createExperienciaLaboralAleatoria(Titulado titulado) {
<add> ExperienciaLaboral experienciaLaboral = new ExperienciaLaboral();
<add> Random random = new Random();
<add>
<add> Calendar calendarFin = new GregorianCalendar();
<add> calendarFin.setTime(GeneradorDatosAleatorios.getFecha(0, 5));
<add> calendarFin.set(Calendar.MILLISECOND, 0);
<add> calendarFin.set(Calendar.SECOND, 0);
<add> calendarFin.set(Calendar.MINUTE, 0);
<add> calendarFin.set(Calendar.HOUR_OF_DAY, 0);
<add> Date fechaFin = calendarFin.getTime();
<add>
<add> Calendar calendarInicio = new GregorianCalendar();
<add> calendarInicio.setTime(fechaFin);
<add> calendarInicio.add(Calendar.DATE, -(random.nextInt(90) + 7));
<add> calendarInicio.set(Calendar.MILLISECOND, 0);
<add> calendarInicio.set(Calendar.SECOND, 0);
<add> calendarInicio.set(Calendar.MINUTE, 0);
<add> calendarInicio.set(Calendar.HOUR_OF_DAY, 0);
<add> Date fechaInicio = calendarInicio.getTime();
<add>
<add> experienciaLaboral.setTitulado(titulado);
<add> experienciaLaboral.setFechaInicio(fechaInicio);
<add> experienciaLaboral.setFechaFin(fechaFin);
<add> experienciaLaboral.setNombreEmpresa(GeneradorDatosAleatorios.getNombreEmpresa());
<add> experienciaLaboral.setPuestoTrabajo(GeneradorDatosAleatorios.getNombrePuestoTrabajo());
<add> experienciaLaboral.setDescripcion("Realizar trabajos relacionados con el puesto de trabajo de " + experienciaLaboral.getPuestoTrabajo());
<add>
<add> return experienciaLaboral;
<add> }
<add>
<add>
<ide> static final public Provincia getProvinciaAleatoria() {
<ide> Random random = new Random();
<ide>
|
|
JavaScript
|
mit
|
34217184e160e8a7e33904ac793ec26b726e752b
| 0 |
plotly/plotly.js,etpinard/plotly.js,asolagmbh/plotly.js,plotly/plotly.js,aburato/plotly.js,plotly/plotly.js,plotly/plotly.js,etpinard/plotly.js,etpinard/plotly.js,aburato/plotly.js,asolagmbh/plotly.js,asolagmbh/plotly.js
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'cs',
dictionary: {
'Autoscale': 'Auto rozsah', // components/modebar/buttons.js:139
'Box Select': 'Obdélníkový výběr', // components/modebar/buttons.js:103
'Click to enter Colorscale title': 'Klikněte pro zadání názvu barevné škály', // plots/plots.js:437
'Click to enter Component A title': 'Klikněte pro zadání názvu komponenty A', // plots/ternary/ternary.js:386
'Click to enter Component B title': 'Klikněte pro zadání názvu komponenty B', // plots/ternary/ternary.js:400
'Click to enter Component C title': 'Klikněte pro zadání názvu komponenty C', // plots/ternary/ternary.js:411
'Click to enter Plot title': 'Klikněte pro zadání názvu grafu', // plot_api/plot_api.js:579
'Click to enter X axis title': 'Klikněte pro zadání názvu osy X', // plots/plots.js:435
'Click to enter Y axis title': 'Klikněte pro zadání názvu osy Y', // plots/plots.js:436
'Compare data on hover': 'Porovnat hodnoty při najetí myší', // components/modebar/buttons.js:167
'Double-click on legend to isolate one trace': 'Dvojklikem na legendu izolujete jedinou datovou sadu', // components/legend/handle_click.js:90
'Double-click to zoom back out': 'Dvojklikem vrátíte zvětšení', // plots/cartesian/dragbox.js:299
'Download plot as a png': 'Uložit jsko PNG', // components/modebar/buttons.js:52
'Edit in Chart Studio': 'Editovat v Chart Studio', // components/modebar/buttons.js:76
'IE only supports svg. Changing format to svg.': 'IE podporuje pouze SVG formát. Změněno na SVG.', // components/modebar/buttons.js:60
'Lasso Select': 'Vyběr lasem', // components/modebar/buttons.js:112
'Orbital rotation': 'Rotace (orbitální)', // components/modebar/buttons.js:279
'Pan': 'Posunovat', // components/modebar/buttons.js:94
'Produced with Plotly': 'Vytvořeno pomocí Plotly', // components/modebar/modebar.js:256
'Reset': 'Obnovit nastavení', // components/modebar/buttons.js:432
'Reset axes': 'Obnovit nastavení os', // components/modebar/buttons.js:148
'Reset camera to default': 'Obnovit nastavení kamery na výchozí stav', // components/modebar/buttons.js:314
'Reset camera to last save': 'Obnovit nastavení kamery na poslední uložený stav', // components/modebar/buttons.js:322
'Reset view': 'Obnovit nastavení pohledu', // components/modebar/buttons.js:583
'Reset views': 'Obnovit nastavení pohledů', // components/modebar/buttons.js:529
'Show closest data on hover': 'Zobrazit najbližší hodnotu při najetí myší', // components/modebar/buttons.js:157
'Snapshot succeeded': 'Snímek vytvořen', // components/modebar/buttons.js:66
'Sorry, there was a problem downloading your snapshot!': 'Omlouváme se, ale došlo k chybě stahování snímku!', // components/modebar/buttons.js:69
'Taking snapshot - this may take a few seconds': 'Vytváří se snímek - může zabrat pár vteřin', // components/modebar/buttons.js:57
'Zoom': 'Zvětšení', // components/modebar/buttons.js:85
'Zoom in': 'Zvětšit', // components/modebar/buttons.js:121
'Zoom out': 'Zmenšit', // components/modebar/buttons.js:130
'close:': 'zavřít:', // traces/ohlc/transform.js:139
'trace': 'datová sada', // plots/plots.js:439
'lat:': 'Lat.:', // traces/scattergeo/calc.js:48
'lon:': 'Lon.:', // traces/scattergeo/calc.js:49
'q1:': 'q1:', // traces/box/calc.js:130
'q3:': 'q3:', // traces/box/calc.js:131
'source:': 'zdroj:', // traces/sankey/plot.js:140
'target:': 'cíl:', // traces/sankey/plot.js:141
'lower fence:': 'dolní limit:', // traces/box/calc.js:134
'upper fence:': 'horní limit:', // traces/box/calc.js:135
'max:': 'max.:', // traces/box/calc.js:132
'mean ± σ:': 'střední ± σ:', // traces/box/calc.js:133
'mean:': 'střední:', // traces/box/calc.js:133
'median:': 'medián:', // traces/box/calc.js:128
'min:': 'min.:', // traces/box/calc.js:129
'Turntable rotation': 'Rotace (otočný stůl)', // components/modebar/buttons.js:288
'Toggle Spike Lines': 'Přepnout zobrazení vodících čar', // components/modebar/buttons.js:548
'open:': 'otevřít:', // traces/ohlc/transform.js:136
'high:': 'horní:', // traces/ohlc/transform.js:137
'low:': 'dolní:', // traces/ohlc/transform.js:138
'Toggle show closest data on hover': 'Přepnout zobrazování nejbližši hodnoty při najetí myší', // components/modebar/buttons.js:353
'incoming flow count:': 'počet dat na vstupu:', // traces/sankey/plot.js:142
'outgoing flow count:': 'počet dat na výstupu:', // traces/sankey/plot.js:143
'kde:': 'kde:' // traces/violin/calc.js:73
},
format: {
days: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
shortDays: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
months: [
'leden', 'únor', 'březen', 'duben', 'květen', 'červen',
'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec'
],
shortMonths: [
'led', 'úno', 'bře', 'dub', 'kvě', 'čer',
'čvc', 'srp', 'zář', 'říj', 'lis', 'pro'
],
date: '%d.%m.%Y'
}
};
|
lib/locales/cs.js
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'cs',
dictionary: {},
format: {
days: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
shortDays: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
months: [
'leden', 'únor', 'březen', 'duben', 'květen', 'červen',
'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec'
],
shortMonths: [
'led', 'úno', 'bře', 'dub', 'kvě', 'čer',
'čvc', 'srp', 'zář', 'říj', 'lis', 'pro'
],
date: '%d.%m.%Y'
}
};
|
Provide Czech translations
|
lib/locales/cs.js
|
Provide Czech translations
|
<ide><path>ib/locales/cs.js
<ide> module.exports = {
<ide> moduleType: 'locale',
<ide> name: 'cs',
<del> dictionary: {},
<add> dictionary: {
<add> 'Autoscale': 'Auto rozsah', // components/modebar/buttons.js:139
<add> 'Box Select': 'Obdélníkový výběr', // components/modebar/buttons.js:103
<add> 'Click to enter Colorscale title': 'Klikněte pro zadání názvu barevné škály', // plots/plots.js:437
<add> 'Click to enter Component A title': 'Klikněte pro zadání názvu komponenty A', // plots/ternary/ternary.js:386
<add> 'Click to enter Component B title': 'Klikněte pro zadání názvu komponenty B', // plots/ternary/ternary.js:400
<add> 'Click to enter Component C title': 'Klikněte pro zadání názvu komponenty C', // plots/ternary/ternary.js:411
<add> 'Click to enter Plot title': 'Klikněte pro zadání názvu grafu', // plot_api/plot_api.js:579
<add> 'Click to enter X axis title': 'Klikněte pro zadání názvu osy X', // plots/plots.js:435
<add> 'Click to enter Y axis title': 'Klikněte pro zadání názvu osy Y', // plots/plots.js:436
<add> 'Compare data on hover': 'Porovnat hodnoty při najetí myší', // components/modebar/buttons.js:167
<add> 'Double-click on legend to isolate one trace': 'Dvojklikem na legendu izolujete jedinou datovou sadu', // components/legend/handle_click.js:90
<add> 'Double-click to zoom back out': 'Dvojklikem vrátíte zvětšení', // plots/cartesian/dragbox.js:299
<add> 'Download plot as a png': 'Uložit jsko PNG', // components/modebar/buttons.js:52
<add> 'Edit in Chart Studio': 'Editovat v Chart Studio', // components/modebar/buttons.js:76
<add> 'IE only supports svg. Changing format to svg.': 'IE podporuje pouze SVG formát. Změněno na SVG.', // components/modebar/buttons.js:60
<add> 'Lasso Select': 'Vyběr lasem', // components/modebar/buttons.js:112
<add> 'Orbital rotation': 'Rotace (orbitální)', // components/modebar/buttons.js:279
<add> 'Pan': 'Posunovat', // components/modebar/buttons.js:94
<add> 'Produced with Plotly': 'Vytvořeno pomocí Plotly', // components/modebar/modebar.js:256
<add> 'Reset': 'Obnovit nastavení', // components/modebar/buttons.js:432
<add> 'Reset axes': 'Obnovit nastavení os', // components/modebar/buttons.js:148
<add> 'Reset camera to default': 'Obnovit nastavení kamery na výchozí stav', // components/modebar/buttons.js:314
<add> 'Reset camera to last save': 'Obnovit nastavení kamery na poslední uložený stav', // components/modebar/buttons.js:322
<add> 'Reset view': 'Obnovit nastavení pohledu', // components/modebar/buttons.js:583
<add> 'Reset views': 'Obnovit nastavení pohledů', // components/modebar/buttons.js:529
<add> 'Show closest data on hover': 'Zobrazit najbližší hodnotu při najetí myší', // components/modebar/buttons.js:157
<add> 'Snapshot succeeded': 'Snímek vytvořen', // components/modebar/buttons.js:66
<add> 'Sorry, there was a problem downloading your snapshot!': 'Omlouváme se, ale došlo k chybě stahování snímku!', // components/modebar/buttons.js:69
<add> 'Taking snapshot - this may take a few seconds': 'Vytváří se snímek - může zabrat pár vteřin', // components/modebar/buttons.js:57
<add> 'Zoom': 'Zvětšení', // components/modebar/buttons.js:85
<add> 'Zoom in': 'Zvětšit', // components/modebar/buttons.js:121
<add> 'Zoom out': 'Zmenšit', // components/modebar/buttons.js:130
<add> 'close:': 'zavřít:', // traces/ohlc/transform.js:139
<add> 'trace': 'datová sada', // plots/plots.js:439
<add> 'lat:': 'Lat.:', // traces/scattergeo/calc.js:48
<add> 'lon:': 'Lon.:', // traces/scattergeo/calc.js:49
<add> 'q1:': 'q1:', // traces/box/calc.js:130
<add> 'q3:': 'q3:', // traces/box/calc.js:131
<add> 'source:': 'zdroj:', // traces/sankey/plot.js:140
<add> 'target:': 'cíl:', // traces/sankey/plot.js:141
<add> 'lower fence:': 'dolní limit:', // traces/box/calc.js:134
<add> 'upper fence:': 'horní limit:', // traces/box/calc.js:135
<add> 'max:': 'max.:', // traces/box/calc.js:132
<add> 'mean ± σ:': 'střední ± σ:', // traces/box/calc.js:133
<add> 'mean:': 'střední:', // traces/box/calc.js:133
<add> 'median:': 'medián:', // traces/box/calc.js:128
<add> 'min:': 'min.:', // traces/box/calc.js:129
<add> 'Turntable rotation': 'Rotace (otočný stůl)', // components/modebar/buttons.js:288
<add> 'Toggle Spike Lines': 'Přepnout zobrazení vodících čar', // components/modebar/buttons.js:548
<add> 'open:': 'otevřít:', // traces/ohlc/transform.js:136
<add> 'high:': 'horní:', // traces/ohlc/transform.js:137
<add> 'low:': 'dolní:', // traces/ohlc/transform.js:138
<add> 'Toggle show closest data on hover': 'Přepnout zobrazování nejbližši hodnoty při najetí myší', // components/modebar/buttons.js:353
<add> 'incoming flow count:': 'počet dat na vstupu:', // traces/sankey/plot.js:142
<add> 'outgoing flow count:': 'počet dat na výstupu:', // traces/sankey/plot.js:143
<add> 'kde:': 'kde:' // traces/violin/calc.js:73
<add> },
<ide> format: {
<ide> days: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
<ide> shortDays: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
|
|
JavaScript
|
mit
|
8bdc30f65ec057590abba1bca5484ab117d6cb95
| 0 |
onaclover/react-native-refreshable-list,onaclover/react-native-refreshable-list,onaclover/react-native-refreshable-list
|
/**
* @providesModule RefreshableList.Main
*/
import React from 'react';
import { ListView, RefreshControl, View } from 'react-native';
import InvertibleScrollView from 'react-native-invertible-scroll-view';
import SGListView from 'react-native-sglistview';
import {
PLACEHOLDER_DATA,
MULTIPLE_SECTIONS_DATASOURCE,
SINGLE_SECTION_DATASOURCE,
} from './constants';
import { hasSectionsDataBlob } from './utils';
export default class RefreshableList extends React.PureComponent {
static propTypes = {
containerStyle: View.propTypes.style,
dataBlob: React.PropTypes.any.isRequired,
hasMoreData: React.PropTypes.bool,
inverted: React.PropTypes.bool,
manualLoadMore: React.PropTypes.bool,
manualReload: React.PropTypes.bool,
onLoadMore: React.PropTypes.func,
onRefresh: React.PropTypes.func,
renderFootLoading: React.PropTypes.func,
renderLoadMore: React.PropTypes.func,
renderPlaceholder: React.PropTypes.func,
renderRow: React.PropTypes.func.isRequired,
usesSGList: React.PropTypes.bool,
};
static defaultProps = {
// Passed props
containerStyle: null,
hasMoreData: true,
inverted: false,
manualLoadMore: false,
manualReload: false,
onLoadMore: null,
onRefresh: null,
renderFootLoading: null,
renderLoadMore: null,
renderPlaceholder: null,
usesSGList: false,
// Default props, will be passed to SGListView
enableEmptySections: true,
initialListSize: 20,
onEndReachedThreshold: 1,
pageSize: 1,
removeClippedSubviews: false,
scrollRenderAheadDistance: 1,
stickyHeaderIndices: [],
};
constructor(props) {
super(props);
this.hasSections = false;
this.mounted = false;
const {
onLoadMore,
onRefresh,
renderFootLoading,
renderLoadMore,
renderPlaceholder,
renderRow,
} = this.props;
// Required props
this.onRefresh = onRefresh.bind(this);
this.renderRow = renderRow.bind(this);
// Optional props
this.onLoadMore = onLoadMore == null ? () => {} : onLoadMore.bind(this);
this.renderFootLoading = renderFootLoading == null ? () => null : renderFootLoading.bind(this);
this.renderLoadMore = renderLoadMore == null ? () => null : renderLoadMore.bind(this);
this.renderPlaceholder = renderPlaceholder == null ? () => null : renderPlaceholder.bind(this);
// Copy defaultStates
this.state = { ...this.defaultStates };
}
componentDidMount() {
this.mounted = true;
!this.props.manualReload && this.reloadData();
}
componentWillReceiveProps(nextProps) {
this.hasSections = hasSectionsDataBlob(nextProps.dataBlob);
}
componentDidUpdate(prevProps) {
const { dataBlob } = this.props;
const { dataBlob: prevDataBlob } = prevProps;
if (dataBlob !== prevDataBlob)
this.populateData();
}
componentWillUnmount() {
this.mounted = false;
}
get clonedDataSource() {
const { dataBlob } = this.props;
return this.hasSections
? MULTIPLE_SECTIONS_DATASOURCE.cloneWithRowsAndSections(dataBlob)
: SINGLE_SECTION_DATASOURCE.cloneWithRows(dataBlob);
}
get placeholderDataSource() {
if (!this.hasSections)
return SINGLE_SECTION_DATASOURCE.cloneWithRows([{ placeholder: true }]);
return MULTIPLE_SECTIONS_DATASOURCE.cloneWithRowsAndSections({
[PLACEHOLDER_DATA]: { [PLACEHOLDER_DATA]: { placeholder: true } },
});
}
get defaultStates() {
return {
currentPage: 1,
dataSource: this.clonedDataSource,
isLoadingMore: false, // Current fetch is to load next page of data
isRefreshing: false, // Current fetch is to refresh all data
isReloading: false, // Reset all states
};
}
get refreshControl() {
if (this.props.onRefresh == null) return null;
return (
<RefreshControl
refreshing={this.state.isRefreshing}
onRefresh={this.refreshData}
{...this.props.refreshControlProps}
/>
);
}
// Public methods
cancelLoading = () => this.updateStates({
isLoadingMore: false,
isRefreshing: false,
isReloading: false,
});
loadMoreData = () => {
const { hasMoreData } = this.props;
if (!hasMoreData) return;
const { currentPage, isLoadingMore, isRefreshing, isReloading } = this.state;
if (isLoadingMore || isRefreshing || isReloading) return;
const page = currentPage + 1;
const newState = { currentPage: page, isLoadingMore: true };
this.updateStates(newState, () => this.onLoadMore({ page, reloading: false }));
};
refreshData = () => {
const newState = { currentPage: 1, isRefreshing: true };
this.updateStates(newState, () => this.onRefresh({ page: 1, reloading: false }));
};
reloadData = () => {
const { isRefreshing, isReloading } = this.state;
if (isRefreshing || isReloading) return;
const newState = { ...this.defaultStates, isReloading: true };
this.updateStates(newState, () => this.onRefresh({ page: 1, reloading: true }));
};
// Private methods
resetScrollOffset = isRefreshing => {
const nativeListView = this.props.usesSGList
? this.listView.getNativeListView()
: this.listView;
isRefreshing && nativeListView.scrollTo({ animated: false, y: 0 });
};
populateData = () => {
const { isRefreshing } = this.state;
const newState = {
dataSource: this.clonedDataSource,
isLoadingMore: false,
isRefreshing: false,
isReloading: false,
};
this.updateStates(newState, () => this.resetScrollOffset(isRefreshing));
};
// State helpers
updateStates = (newState, callback) => {
if (!this.mounted) return;
this.setState(newState, callback);
}
onEndReached = () => {
const { manualLoadMore, onLoadMore } = this.props;
!manualLoadMore && onLoadMore != null && this.loadMoreData();
};
renderFooter = () => {
const { hasMoreData, renderFooter } = this.props;
const { isLoadingMore, isRefreshing, isReloading } = this.state;
const shouldRenderLoadMore = hasMoreData && !isLoadingMore && !isRefreshing && !isReloading;
const footLoadingRenderer = isLoadingMore ? this.renderFootLoading : () => null;
const loadMoreRenderer = shouldRenderLoadMore ? this.renderLoadMore : footLoadingRenderer;
return loadMoreRenderer != null ? loadMoreRenderer() : renderFooter.bind(this)();
};
renderScrollComponent = props => <InvertibleScrollView {...props} />;
render() {
const { containerStyle, usesSGList } = this.props;
const { isReloading } = this.state;
const dataSource = isReloading ? this.placeholderDataSource : this.state.dataSource;
const renderRow = isReloading ? this.renderPlaceholder : this.renderRow;
const ListViewComponent = usesSGList ? SGListView : ListView;
const listContent = (
<ListViewComponent
{...this.props}
dataSource={dataSource}
onEndReached={this.onEndReached}
ref={ref => this.listView = ref}
refreshControl={this.refreshControl}
renderFooter={this.renderFooter}
renderRow={renderRow}
renderScrollComponent={this.renderScrollComponent}
/>
);
if (containerStyle == null)
return listContent;
return (
<View style={containerStyle}>
{listContent}
</View>
);
}
}
|
src/RefreshableList.js
|
/**
* @providesModule RefreshableList.Main
*/
import React from 'react';
import { ListView, RefreshControl, View } from 'react-native';
import InvertibleScrollView from 'react-native-invertible-scroll-view';
import SGListView from 'react-native-sglistview';
import {
PLACEHOLDER_DATA,
MULTIPLE_SECTIONS_DATASOURCE,
SINGLE_SECTION_DATASOURCE,
} from './constants';
import { hasSectionsDataBlob } from './utils';
export default class RefreshableList extends React.PureComponent {
static propTypes = {
containerStyle: View.propTypes.style,
dataBlob: React.PropTypes.any.isRequired,
hasMoreData: React.PropTypes.bool,
inverted: React.PropTypes.bool,
manualLoadMore: React.PropTypes.bool,
manualReload: React.PropTypes.bool,
onLoadMore: React.PropTypes.func,
onRefresh: React.PropTypes.func,
renderFootLoading: React.PropTypes.func,
renderLoadMore: React.PropTypes.func,
renderPlaceholder: React.PropTypes.func,
renderRow: React.PropTypes.func.isRequired,
usesSGList: React.PropTypes.bool,
};
static defaultProps = {
// Passed props
containerStyle: null,
hasMoreData: true,
inverted: false,
manualLoadMore: false,
manualReload: false,
onLoadMore: null,
onRefresh: null,
renderFootLoading: null,
renderLoadMore: null,
renderPlaceholder: null,
usesSGList: false,
// Default props, will be passed to SGListView
enableEmptySections: true,
initialListSize: 20,
onEndReachedThreshold: 1,
pageSize: 1,
removeClippedSubviews: false,
scrollRenderAheadDistance: 1,
stickyHeaderIndices: [],
};
constructor(props) {
super(props);
this.hasSections = false;
this.mounted = false;
const {
onLoadMore,
onRefresh,
renderFootLoading,
renderLoadMore,
renderPlaceholder,
renderRow,
} = this.props;
// Required props
this.onRefresh = onRefresh.bind(this);
this.renderRow = renderRow.bind(this);
// Optional props
this.onLoadMore = onLoadMore == null ? () => {} : onLoadMore.bind(this);
this.renderFootLoading = renderFootLoading == null ? () => null : renderFootLoading.bind(this);
this.renderLoadMore = renderLoadMore == null ? () => null : renderLoadMore.bind(this);
this.renderPlaceholder = renderPlaceholder == null ? () => null : renderPlaceholder.bind(this);
// Copy defaultStates
this.state = { ...this.defaultStates };
}
componentDidMount() {
this.mounted = true;
!this.props.manualReload && this.reloadData();
}
componentWillReceiveProps(nextProps) {
this.hasSections = hasSectionsDataBlob(nextProps.dataBlob);
}
componentDidUpdate(prevProps) {
const { dataBlob } = this.props;
const { dataBlob: prevDataBlob } = prevProps;
if (dataBlob !== prevDataBlob)
this.populateData();
}
componentWillUnmount() {
this.mounted = false;
}
get clonedDataSource() {
const { dataBlob } = this.props;
return this.hasSections
? MULTIPLE_SECTIONS_DATASOURCE.cloneWithRowsAndSections(dataBlob)
: SINGLE_SECTION_DATASOURCE.cloneWithRows(dataBlob);
}
get placeholderDataSource() {
if (!this.hasSections)
return SINGLE_SECTION_DATASOURCE.cloneWithRows([{ placeholder: true }]);
return MULTIPLE_SECTIONS_DATASOURCE.cloneWithRowsAndSections({
[PLACEHOLDER_DATA]: { [PLACEHOLDER_DATA]: { placeholder: true } },
});
}
get defaultStates() {
return {
currentPage: 1,
dataSource: this.clonedDataSource,
isLoadingMore: false, // Current fetch is to load next page of data
isRefreshing: false, // Current fetch is to refresh all data
isReloading: false, // Reset all states
};
}
get refreshControl() {
if (this.props.onRefresh == null) return null;
return (
<RefreshControl
refreshing={this.state.isRefreshing}
onRefresh={this.refreshData}
{...this.props.refreshControlProps}
/>
);
}
// Public methods
cancelLoading = () => this.updateStates({
isLoadingMore: false,
isRefreshing: false,
isReloading: false,
});
loadMoreData = () => {
const { hasMoreData } = this.props;
if (!hasMoreData) return;
const { currentPage, isLoadingMore, isRefreshing, isReloading } = this.state;
if (isLoadingMore || isRefreshing || isReloading) return;
const newState = { currentPage: currentPage + 1, isLoadingMore: true };
this.updateStates(newState, () => this.onLoadMore(currentPage + 1));
};
refreshData = () => {
const newState = { currentPage: 1, isRefreshing: true };
this.updateStates(newState, () => this.onRefresh({ reloading: false }));
};
reloadData = () => {
const { isRefreshing, isReloading } = this.state;
if (isRefreshing || isReloading) return;
const newState = { ...this.defaultStates, isReloading: true };
this.updateStates(newState, () => this.onRefresh({ reloading: true }));
};
// Private methods
resetScrollOffset = isRefreshing => {
const nativeListView = this.props.usesSGList
? this.listView.getNativeListView()
: this.listView;
isRefreshing && nativeListView.scrollTo({ animated: false, y: 0 });
};
populateData = () => {
const { isRefreshing } = this.state;
const newState = {
dataSource: this.clonedDataSource,
isLoadingMore: false,
isRefreshing: false,
isReloading: false,
};
this.updateStates(newState, () => this.resetScrollOffset(isRefreshing));
};
// State helpers
updateStates = (newState, callback) => {
if (!this.mounted) return;
this.setState(newState, callback);
}
onEndReached = () => {
const { manualLoadMore, onLoadMore } = this.props;
!manualLoadMore && onLoadMore != null && this.loadMoreData();
};
renderFooter = () => {
const { hasMoreData, renderFooter } = this.props;
const { isLoadingMore, isRefreshing, isReloading } = this.state;
const shouldRenderLoadMore = hasMoreData && !isLoadingMore && !isRefreshing && !isReloading;
const footLoadingRenderer = isLoadingMore ? this.renderFootLoading : () => null;
const loadMoreRenderer = shouldRenderLoadMore ? this.renderLoadMore : footLoadingRenderer;
return loadMoreRenderer != null ? loadMoreRenderer() : renderFooter.bind(this)();
};
renderScrollComponent = props => <InvertibleScrollView {...props} />;
render() {
const { containerStyle, usesSGList } = this.props;
const { isReloading } = this.state;
const dataSource = isReloading ? this.placeholderDataSource : this.state.dataSource;
const renderRow = isReloading ? this.renderPlaceholder : this.renderRow;
const ListViewComponent = usesSGList ? SGListView : ListView;
const listContent = (
<ListViewComponent
{...this.props}
dataSource={dataSource}
onEndReached={this.onEndReached}
ref={ref => this.listView = ref}
refreshControl={this.refreshControl}
renderFooter={this.renderFooter}
renderRow={renderRow}
renderScrollComponent={this.renderScrollComponent}
/>
);
if (containerStyle == null)
return listContent;
return (
<View style={containerStyle}>
{listContent}
</View>
);
}
}
|
Pass object to onLoadMore & onRefresh
|
src/RefreshableList.js
|
Pass object to onLoadMore & onRefresh
|
<ide><path>rc/RefreshableList.js
<ide> const { currentPage, isLoadingMore, isRefreshing, isReloading } = this.state;
<ide> if (isLoadingMore || isRefreshing || isReloading) return;
<ide>
<del> const newState = { currentPage: currentPage + 1, isLoadingMore: true };
<del> this.updateStates(newState, () => this.onLoadMore(currentPage + 1));
<add> const page = currentPage + 1;
<add> const newState = { currentPage: page, isLoadingMore: true };
<add> this.updateStates(newState, () => this.onLoadMore({ page, reloading: false }));
<ide> };
<ide>
<ide> refreshData = () => {
<ide> const newState = { currentPage: 1, isRefreshing: true };
<del> this.updateStates(newState, () => this.onRefresh({ reloading: false }));
<add> this.updateStates(newState, () => this.onRefresh({ page: 1, reloading: false }));
<ide> };
<ide>
<ide> reloadData = () => {
<ide> if (isRefreshing || isReloading) return;
<ide>
<ide> const newState = { ...this.defaultStates, isReloading: true };
<del> this.updateStates(newState, () => this.onRefresh({ reloading: true }));
<add> this.updateStates(newState, () => this.onRefresh({ page: 1, reloading: true }));
<ide> };
<ide>
<ide> // Private methods
|
|
Java
|
apache-2.0
|
aa28bc06130a5cfb595425efb87727d59df098e0
| 0 |
mangeshpardeshiyahoo/druid,Deebs21/druid,du00cs/druid,Deebs21/druid,KurtYoung/druid,Fokko/druid,andy256/druid,milimetric/druid,gianm/druid,nvoron23/druid,qix/druid,jon-wei/druid,wenjixin/druid,jon-wei/druid,mangeshpardeshiyahoo/druid,potto007/druid-avro,michaelschiff/druid,premc/druid,andy256/druid,mrijke/druid,haoch/druid,mghosh4/druid,erikdubbelboer/druid,nishantmonu51/druid,wenjixin/druid,noddi/druid,zengzhihai110/druid,optimizely/druid,pjain1/druid,dclim/druid,authbox-lib/druid,leventov/druid,lizhanhui/data_druid,nvoron23/druid,minewhat/druid,calliope7/druid,yaochitc/druid-dev,b-slim/druid,liquidm/druid,yaochitc/druid-dev,dkhwangbo/druid,guobingkun/druid,cocosli/druid,rasahner/druid,anupkumardixit/druid,implydata/druid,kevintvh/druid,zengzhihai110/druid,nishantmonu51/druid,redBorder/druid,mangeshpardeshiyahoo/druid,penuel-leo/druid,nishantmonu51/druid,premc/druid,solimant/druid,mrijke/druid,druid-io/druid,pdeva/druid,yaochitc/druid-dev,elijah513/druid,pombredanne/druid,michaelschiff/druid,anupkumardixit/druid,liquidm/druid,nishantmonu51/druid,haoch/druid,mghosh4/druid,lcp0578/druid,b-slim/druid,winval/druid,mrijke/druid,nishantmonu51/druid,dclim/druid,pjain1/druid,Deebs21/druid,qix/druid,friedhardware/druid,solimant/druid,nvoron23/druid,haoch/druid,minewhat/druid,cocosli/druid,friedhardware/druid,erikdubbelboer/druid,dclim/druid,metamx/druid,metamx/druid,elijah513/druid,deltaprojects/druid,deltaprojects/druid,deltaprojects/druid,zengzhihai110/druid,himanshug/druid,dclim/druid,fjy/druid,elijah513/druid,erikdubbelboer/druid,skyportsystems/druid,zhihuij/druid,eshen1991/druid,winval/druid,Kleagleguo/druid,himanshug/druid,se7entyse7en/druid,anupkumardixit/druid,friedhardware/druid,elijah513/druid,pdeva/druid,druid-io/druid,noddi/druid,smartpcr/druid,rasahner/druid,implydata/druid,michaelschiff/druid,fjy/druid,liquidm/druid,du00cs/druid,calliope7/druid,767326791/druid,pjain1/druid,zhiqinghuang/druid,authbox-lib/druid,se7entyse7en/druid,mghosh4/druid,yaochitc/druid-dev,mangeshpardeshiyahoo/druid,pombredanne/druid,penuel-leo/druid,OttoOps/druid,zxs/druid,pjain1/druid,lizhanhui/data_druid,redBorder/druid,pjain1/druid,skyportsystems/druid,du00cs/druid,milimetric/druid,mghosh4/druid,zhihuij/druid,tubemogul/druid,lcp0578/druid,liquidm/druid,potto007/druid-avro,zhaown/druid,mrijke/druid,zhaown/druid,authbox-lib/druid,zhiqinghuang/druid,Kleagleguo/druid,Fokko/druid,guobingkun/druid,optimizely/druid,solimant/druid,skyportsystems/druid,himanshug/druid,himanshug/druid,mrijke/druid,nishantmonu51/druid,zengzhihai110/druid,lcp0578/druid,se7entyse7en/druid,smartpcr/druid,dkhwangbo/druid,skyportsystems/druid,knoguchi/druid,authbox-lib/druid,redBorder/druid,haoch/druid,metamx/druid,druid-io/druid,mangeshpardeshiyahoo/druid,b-slim/druid,fjy/druid,liquidm/druid,zxs/druid,amikey/druid,zhihuij/druid,optimizely/druid,milimetric/druid,monetate/druid,potto007/druid-avro,amikey/druid,Kleagleguo/druid,zhiqinghuang/druid,noddi/druid,calliope7/druid,zhiqinghuang/druid,friedhardware/druid,mghosh4/druid,haoch/druid,gianm/druid,pdeva/druid,jon-wei/druid,winval/druid,tubemogul/druid,Fokko/druid,knoguchi/druid,pdeva/druid,optimizely/druid,premc/druid,noddi/druid,smartpcr/druid,qix/druid,zxs/druid,eshen1991/druid,fjy/druid,OttoOps/druid,pombredanne/druid,leventov/druid,michaelschiff/druid,taochaoqiang/druid,knoguchi/druid,solimant/druid,taochaoqiang/druid,jon-wei/druid,monetate/druid,taochaoqiang/druid,wenjixin/druid,du00cs/druid,lizhanhui/data_druid,penuel-leo/druid,knoguchi/druid,taochaoqiang/druid,gianm/druid,praveev/druid,zengzhihai110/druid,zxs/druid,OttoOps/druid,KurtYoung/druid,wenjixin/druid,smartpcr/druid,kevintvh/druid,zhihuij/druid,KurtYoung/druid,767326791/druid,noddi/druid,dkhwangbo/druid,elijah513/druid,rasahner/druid,deltaprojects/druid,monetate/druid,Fokko/druid,tubemogul/druid,pombredanne/druid,anupkumardixit/druid,767326791/druid,potto007/druid-avro,deltaprojects/druid,Deebs21/druid,liquidm/druid,lcp0578/druid,767326791/druid,winval/druid,pjain1/druid,implydata/druid,zhaown/druid,premc/druid,calliope7/druid,Kleagleguo/druid,eshen1991/druid,b-slim/druid,dclim/druid,metamx/druid,dkhwangbo/druid,redBorder/druid,minewhat/druid,taochaoqiang/druid,KurtYoung/druid,implydata/druid,amikey/druid,michaelschiff/druid,yaochitc/druid-dev,mghosh4/druid,zhihuij/druid,andy256/druid,winval/druid,cocosli/druid,guobingkun/druid,erikdubbelboer/druid,zhiqinghuang/druid,gianm/druid,zhaown/druid,gianm/druid,Fokko/druid,optimizely/druid,pjain1/druid,redBorder/druid,implydata/druid,praveev/druid,praveev/druid,tubemogul/druid,monetate/druid,minewhat/druid,deltaprojects/druid,premc/druid,Fokko/druid,guobingkun/druid,cocosli/druid,penuel-leo/druid,monetate/druid,minewhat/druid,Kleagleguo/druid,eshen1991/druid,anupkumardixit/druid,wenjixin/druid,mghosh4/druid,cocosli/druid,leventov/druid,fjy/druid,smartpcr/druid,knoguchi/druid,penuel-leo/druid,767326791/druid,andy256/druid,Deebs21/druid,potto007/druid-avro,jon-wei/druid,kevintvh/druid,nvoron23/druid,calliope7/druid,praveev/druid,rasahner/druid,zxs/druid,michaelschiff/druid,pombredanne/druid,OttoOps/druid,implydata/druid,kevintvh/druid,lcp0578/druid,se7entyse7en/druid,druid-io/druid,qix/druid,druid-io/druid,jon-wei/druid,monetate/druid,pdeva/druid,Fokko/druid,andy256/druid,lizhanhui/data_druid,se7entyse7en/druid,b-slim/druid,skyportsystems/druid,gianm/druid,eshen1991/druid,zhaown/druid,friedhardware/druid,monetate/druid,milimetric/druid,leventov/druid,jon-wei/druid,dkhwangbo/druid,lizhanhui/data_druid,metamx/druid,michaelschiff/druid,nishantmonu51/druid,qix/druid,amikey/druid,kevintvh/druid,du00cs/druid,leventov/druid,deltaprojects/druid,gianm/druid,himanshug/druid,guobingkun/druid,milimetric/druid,OttoOps/druid,rasahner/druid,nvoron23/druid,erikdubbelboer/druid,amikey/druid,authbox-lib/druid,praveev/druid,KurtYoung/druid,solimant/druid,tubemogul/druid
|
/*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.druid.client;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.metamx.common.IAE;
import com.metamx.common.Pair;
import com.metamx.common.RE;
import com.metamx.common.guava.BaseSequence;
import com.metamx.common.guava.CloseQuietly;
import com.metamx.common.guava.Sequence;
import com.metamx.common.guava.Sequences;
import com.metamx.common.logger.Logger;
import com.metamx.http.client.HttpClient;
import com.metamx.http.client.io.AppendableByteArrayInputStream;
import com.metamx.http.client.response.ClientResponse;
import com.metamx.http.client.response.InputStreamResponseHandler;
import com.metamx.http.client.response.StatusResponseHandler;
import com.metamx.http.client.response.StatusResponseHolder;
import io.druid.query.BySegmentResultValueClass;
import io.druid.query.Query;
import io.druid.query.QueryInterruptedException;
import io.druid.query.QueryRunner;
import io.druid.query.QueryToolChest;
import io.druid.query.QueryToolChestWarehouse;
import io.druid.query.QueryWatcher;
import io.druid.query.Result;
import io.druid.query.aggregation.MetricManipulatorFns;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
/**
*/
public class DirectDruidClient<T> implements QueryRunner<T>
{
private static final Logger log = new Logger(DirectDruidClient.class);
private static final Map<Class<? extends Query>, Pair<JavaType, JavaType>> typesMap = Maps.newConcurrentMap();
private final QueryToolChestWarehouse warehouse;
private final QueryWatcher queryWatcher;
private final ObjectMapper objectMapper;
private final HttpClient httpClient;
private final String host;
private final AtomicInteger openConnections;
private final boolean isSmile;
public DirectDruidClient(
QueryToolChestWarehouse warehouse,
QueryWatcher queryWatcher,
ObjectMapper objectMapper,
HttpClient httpClient,
String host
)
{
this.warehouse = warehouse;
this.queryWatcher = queryWatcher;
this.objectMapper = objectMapper;
this.httpClient = httpClient;
this.host = host;
this.isSmile = this.objectMapper.getFactory() instanceof SmileFactory;
this.openConnections = new AtomicInteger();
}
public int getNumOpenConnections()
{
return openConnections.get();
}
@Override
public Sequence<T> run(final Query<T> query, final Map<String, Object> context)
{
QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query);
boolean isBySegment = query.getContextBySegment(false);
Pair<JavaType, JavaType> types = typesMap.get(query.getClass());
if (types == null) {
final TypeFactory typeFactory = objectMapper.getTypeFactory();
JavaType baseType = typeFactory.constructType(toolChest.getResultTypeReference());
JavaType bySegmentType = typeFactory.constructParametricType(
Result.class, typeFactory.constructParametricType(BySegmentResultValueClass.class, baseType)
);
types = Pair.of(baseType, bySegmentType);
typesMap.put(query.getClass(), types);
}
final JavaType typeRef;
if (isBySegment) {
typeRef = types.rhs;
} else {
typeRef = types.lhs;
}
final ListenableFuture<InputStream> future;
final String url = String.format("http://%s/druid/v2/", host);
final String cancelUrl = String.format("http://%s/druid/v2/%s", host, query.getId());
try {
log.debug("Querying url[%s]", url);
future = httpClient
.post(new URL(url))
.setContent(objectMapper.writeValueAsBytes(query))
.setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? "application/smile" : "application/json")
.go(
new InputStreamResponseHandler()
{
long startTime;
long byteCount = 0;
@Override
public ClientResponse<AppendableByteArrayInputStream> handleResponse(HttpResponse response)
{
log.debug("Initial response from url[%s]", url);
startTime = System.currentTimeMillis();
byteCount += response.getContent().readableBytes();
try {
final Map<String, Object> responseContext = objectMapper.readValue(
response.headers().get("X-Druid-Response-Context"), new TypeReference<Map<String, Object>>()
{
}
);
context.putAll(responseContext);
}
catch (IOException e) {
e.printStackTrace();
}
return super.handleResponse(response);
}
@Override
public ClientResponse<AppendableByteArrayInputStream> handleChunk(
ClientResponse<AppendableByteArrayInputStream> clientResponse, HttpChunk chunk
)
{
final int bytes = chunk.getContent().readableBytes();
byteCount += bytes;
return super.handleChunk(clientResponse, chunk);
}
@Override
public ClientResponse<InputStream> done(ClientResponse<AppendableByteArrayInputStream> clientResponse)
{
long stopTime = System.currentTimeMillis();
log.debug(
"Completed request to url[%s] with %,d bytes returned in %,d millis [%,f b/s].",
url,
byteCount,
stopTime - startTime,
byteCount / (0.0001 * (stopTime - startTime))
);
return super.done(clientResponse);
}
}
);
queryWatcher.registerQuery(query, future);
openConnections.getAndIncrement();
Futures.addCallback(
future, new FutureCallback<InputStream>()
{
@Override
public void onSuccess(InputStream result)
{
openConnections.getAndDecrement();
}
@Override
public void onFailure(Throwable t)
{
openConnections.getAndDecrement();
if (future.isCancelled()) {
// forward the cancellation to underlying queriable node
try {
StatusResponseHolder res = httpClient
.delete(new URL(cancelUrl))
.setContent(objectMapper.writeValueAsBytes(query))
.setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? "application/smile" : "application/json")
.go(new StatusResponseHandler(Charsets.UTF_8))
.get();
if (res.getStatus().getCode() >= 500) {
throw new RE(
"Error cancelling query[%s]: queriable node returned status[%d] [%s].",
res.getStatus().getCode(),
res.getStatus().getReasonPhrase()
);
}
}
catch (IOException | ExecutionException | InterruptedException e) {
Throwables.propagate(e);
}
}
}
}
);
}
catch (IOException e) {
throw Throwables.propagate(e);
}
Sequence<T> retVal = new BaseSequence<>(
new BaseSequence.IteratorMaker<T, JsonParserIterator<T>>()
{
@Override
public JsonParserIterator<T> make()
{
return new JsonParserIterator<T>(typeRef, future, url);
}
@Override
public void cleanup(JsonParserIterator<T> iterFromMake)
{
CloseQuietly.close(iterFromMake);
}
}
);
if (!isBySegment) {
retVal = Sequences.map(
retVal,
toolChest.makePreComputeManipulatorFn(
query,
MetricManipulatorFns.deserializing()
)
);
}
return retVal;
}
private class JsonParserIterator<T> implements Iterator<T>, Closeable
{
private JsonParser jp;
private ObjectCodec objectCodec;
private final JavaType typeRef;
private final Future<InputStream> future;
private final String url;
public JsonParserIterator(JavaType typeRef, Future<InputStream> future, String url)
{
this.typeRef = typeRef;
this.future = future;
this.url = url;
jp = null;
}
@Override
public boolean hasNext()
{
init();
if (jp.isClosed()) {
return false;
}
if (jp.getCurrentToken() == JsonToken.END_ARRAY) {
CloseQuietly.close(jp);
return false;
}
return true;
}
@Override
public T next()
{
init();
try {
final T retVal = objectCodec.readValue(jp, typeRef);
jp.nextToken();
return retVal;
}
catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
private void init()
{
if (jp == null) {
try {
jp = objectMapper.getFactory().createParser(future.get());
final JsonToken nextToken = jp.nextToken();
if (nextToken == JsonToken.START_OBJECT) {
QueryInterruptedException e = jp.getCodec().readValue(jp, QueryInterruptedException.class);
throw e;
} else if (nextToken != JsonToken.START_ARRAY) {
throw new IAE("Next token wasn't a START_ARRAY, was[%s] from url [%s]", jp.getCurrentToken(), url);
} else {
jp.nextToken();
objectCodec = jp.getCodec();
}
}
catch (IOException | InterruptedException | ExecutionException e) {
throw new RE(e, "Failure getting results from[%s] because of [%s]", url, e.getMessage());
}
catch (CancellationException e) {
throw new QueryInterruptedException("Query cancelled");
}
}
}
@Override
public void close() throws IOException
{
if (jp != null) {
jp.close();
}
}
}
}
|
server/src/main/java/io/druid/client/DirectDruidClient.java
|
/*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.druid.client;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.metamx.common.IAE;
import com.metamx.common.Pair;
import com.metamx.common.RE;
import com.metamx.common.guava.BaseSequence;
import com.metamx.common.guava.CloseQuietly;
import com.metamx.common.guava.Sequence;
import com.metamx.common.guava.Sequences;
import com.metamx.common.logger.Logger;
import com.metamx.http.client.HttpClient;
import com.metamx.http.client.io.AppendableByteArrayInputStream;
import com.metamx.http.client.response.ClientResponse;
import com.metamx.http.client.response.InputStreamResponseHandler;
import com.metamx.http.client.response.StatusResponseHandler;
import com.metamx.http.client.response.StatusResponseHolder;
import io.druid.query.BySegmentResultValueClass;
import io.druid.query.Query;
import io.druid.query.QueryInterruptedException;
import io.druid.query.QueryRunner;
import io.druid.query.QueryToolChest;
import io.druid.query.QueryToolChestWarehouse;
import io.druid.query.QueryWatcher;
import io.druid.query.Result;
import io.druid.query.aggregation.MetricManipulatorFns;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
/**
*/
public class DirectDruidClient<T> implements QueryRunner<T>
{
private static final Logger log = new Logger(DirectDruidClient.class);
private static final Map<Class<? extends Query>, Pair<JavaType, JavaType>> typesMap = Maps.newConcurrentMap();
private final QueryToolChestWarehouse warehouse;
private final QueryWatcher queryWatcher;
private final ObjectMapper objectMapper;
private final HttpClient httpClient;
private final String host;
private final AtomicInteger openConnections;
private final boolean isSmile;
public DirectDruidClient(
QueryToolChestWarehouse warehouse,
QueryWatcher queryWatcher,
ObjectMapper objectMapper,
HttpClient httpClient,
String host
)
{
this.warehouse = warehouse;
this.queryWatcher = queryWatcher;
this.objectMapper = objectMapper;
this.httpClient = httpClient;
this.host = host;
this.isSmile = this.objectMapper.getFactory() instanceof SmileFactory;
this.openConnections = new AtomicInteger();
}
public int getNumOpenConnections()
{
return openConnections.get();
}
@Override
public Sequence<T> run(final Query<T> query, final Map<String, Object> context)
{
QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query);
boolean isBySegment = query.getContextBySegment(false);
Pair<JavaType, JavaType> types = typesMap.get(query.getClass());
if (types == null) {
final TypeFactory typeFactory = objectMapper.getTypeFactory();
JavaType baseType = typeFactory.constructType(toolChest.getResultTypeReference());
JavaType bySegmentType = typeFactory.constructParametricType(
Result.class, typeFactory.constructParametricType(BySegmentResultValueClass.class, baseType)
);
types = Pair.of(baseType, bySegmentType);
typesMap.put(query.getClass(), types);
}
final JavaType typeRef;
if (isBySegment) {
typeRef = types.rhs;
} else {
typeRef = types.lhs;
}
final ListenableFuture<InputStream> future;
final String url = String.format("http://%s/druid/v2/", host);
final String cancelUrl = String.format("http://%s/druid/v2/%s", host, query.getId());
try {
log.debug("Querying url[%s]", url);
future = httpClient
.post(new URL(url))
.setContent(objectMapper.writeValueAsBytes(query))
.setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? "application/smile" : "application/json")
.go(
new InputStreamResponseHandler()
{
long startTime;
long byteCount = 0;
@Override
public ClientResponse<AppendableByteArrayInputStream> handleResponse(HttpResponse response)
{
log.debug("Initial response from url[%s]", url);
startTime = System.currentTimeMillis();
byteCount += response.getContent().readableBytes();
try {
final Map<String, Object> responseContext = objectMapper.readValue(
response.headers().get("X-Druid-Response-Context"), new TypeReference<Map<String, Object>>()
{
}
);
context.putAll(responseContext);
}
catch (IOException e) {
e.printStackTrace();
}
return super.handleResponse(response);
}
@Override
public ClientResponse<AppendableByteArrayInputStream> handleChunk(
ClientResponse<AppendableByteArrayInputStream> clientResponse, HttpChunk chunk
)
{
final int bytes = chunk.getContent().readableBytes();
byteCount += bytes;
return super.handleChunk(clientResponse, chunk);
}
@Override
public ClientResponse<InputStream> done(ClientResponse<AppendableByteArrayInputStream> clientResponse)
{
long stopTime = System.currentTimeMillis();
log.debug(
"Completed request to url[%s] with %,d bytes returned in %,d millis [%,f b/s].",
url,
byteCount,
stopTime - startTime,
byteCount / (0.0001 * (stopTime - startTime))
);
return super.done(clientResponse);
}
}
);
queryWatcher.registerQuery(query, future);
openConnections.getAndIncrement();
Futures.addCallback(
future, new FutureCallback<InputStream>()
{
@Override
public void onSuccess(InputStream result)
{
openConnections.getAndDecrement();
}
@Override
public void onFailure(Throwable t)
{
openConnections.getAndDecrement();
if (future.isCancelled()) {
// forward the cancellation to underlying queriable node
try {
StatusResponseHolder res = httpClient
.delete(new URL(cancelUrl))
.setContent(objectMapper.writeValueAsBytes(query))
.setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? "application/smile" : "application/json")
.go(new StatusResponseHandler(Charsets.UTF_8))
.get();
if (res.getStatus().getCode() >= 500) {
throw new RE(
"Error cancelling query[%s]: queriable node returned status[%d] [%s].",
res.getStatus().getCode(),
res.getStatus().getReasonPhrase()
);
}
}
catch (IOException | ExecutionException | InterruptedException e) {
Throwables.propagate(e);
}
}
}
}
);
}
catch (IOException e) {
throw Throwables.propagate(e);
}
Sequence<T> retVal = new BaseSequence<>(
new BaseSequence.IteratorMaker<T, JsonParserIterator<T>>()
{
@Override
public JsonParserIterator<T> make()
{
return new JsonParserIterator<T>(typeRef, future, url);
}
@Override
public void cleanup(JsonParserIterator<T> iterFromMake)
{
CloseQuietly.close(iterFromMake);
}
}
);
if (!isBySegment) {
retVal = Sequences.map(
retVal,
toolChest.makePreComputeManipulatorFn(
query,
MetricManipulatorFns.deserializing()
)
);
}
return retVal;
}
private class JsonParserIterator<T> implements Iterator<T>, Closeable
{
private JsonParser jp;
private ObjectCodec objectCodec;
private final JavaType typeRef;
private final Future<InputStream> future;
private final String url;
public JsonParserIterator(JavaType typeRef, Future<InputStream> future, String url)
{
this.typeRef = typeRef;
this.future = future;
this.url = url;
jp = null;
}
@Override
public boolean hasNext()
{
init();
if (jp.isClosed()) {
return false;
}
if (jp.getCurrentToken() == JsonToken.END_ARRAY) {
CloseQuietly.close(jp);
return false;
}
return true;
}
@Override
public T next()
{
init();
try {
final T retVal = objectCodec.readValue(jp, typeRef);
jp.nextToken();
return retVal;
}
catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
private void init()
{
if (jp == null) {
try {
jp = objectMapper.getFactory().createParser(future.get());
final JsonToken nextToken = jp.nextToken();
if (nextToken == JsonToken.START_OBJECT) {
QueryInterruptedException e = jp.getCodec().readValue(jp, QueryInterruptedException.class);
throw e;
} else if (nextToken != JsonToken.START_ARRAY) {
throw new IAE("Next token wasn't a START_ARRAY, was[%s] from url [%s]", jp.getCurrentToken(), url);
} else {
jp.nextToken();
objectCodec = jp.getCodec();
}
}
catch (IOException | InterruptedException | ExecutionException e) {
throw new RE(e, "Failure getting results from[%s]. Likely a timeout occurred.", url);
}
catch (CancellationException e) {
throw new QueryInterruptedException("Query cancelled");
}
}
}
@Override
public void close() throws IOException
{
if (jp != null) {
jp.close();
}
}
}
}
|
address cr
|
server/src/main/java/io/druid/client/DirectDruidClient.java
|
address cr
|
<ide><path>erver/src/main/java/io/druid/client/DirectDruidClient.java
<ide> }
<ide> }
<ide> catch (IOException | InterruptedException | ExecutionException e) {
<del> throw new RE(e, "Failure getting results from[%s]. Likely a timeout occurred.", url);
<add> throw new RE(e, "Failure getting results from[%s] because of [%s]", url, e.getMessage());
<ide> }
<ide> catch (CancellationException e) {
<ide> throw new QueryInterruptedException("Query cancelled");
|
|
Java
|
mit
|
aee42bb108aef90eba0a12ff05ab9afceae9b543
| 0 |
diegotori/robolectric,jongerrish/robolectric,ocadotechnology/robolectric,ChengCorp/robolectric,diegotori/robolectric,diegotori/robolectric,cesar1000/robolectric,spotify/robolectric,jongerrish/robolectric,ChengCorp/robolectric,ocadotechnology/robolectric,cesar1000/robolectric,ChengCorp/robolectric,jongerrish/robolectric,ocadotechnology/robolectric,spotify/robolectric,spotify/robolectric,cesar1000/robolectric,jongerrish/robolectric
|
package org.robolectric.shadows;
import android.telephony.CellLocation;
import android.telephony.CellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.TestRunners;
import static android.content.Context.TELEPHONY_SERVICE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.robolectric.RuntimeEnvironment.*;
import static org.robolectric.Shadows.shadowOf;
import static org.robolectric.internal.Shadow.newInstanceOf;
@RunWith(TestRunners.MultiApiWithDefaults.class)
public class ShadowTelephonyManagerTest {
private TelephonyManager manager;
private ShadowTelephonyManager shadowManager;
private MyPhoneStateListener listener;
@Before
public void setUp() throws Exception {
manager = newInstanceOf(TelephonyManager.class);
shadowManager = shadowOf(manager);
listener = new MyPhoneStateListener();
}
@Test
public void testListen() {
manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
assertThat(shadowManager.getListener()).isNotNull();
assertThat((MyPhoneStateListener) shadowManager.getListener()).isSameAs(listener);
assertThat(shadowManager.getEventFlags()).isEqualTo(PhoneStateListener.LISTEN_CALL_STATE);
}
@Test
public void shouldGiveDeviceId() {
String testId = "TESTING123";
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
shadowOf(telephonyManager).setDeviceId(testId);
assertEquals(testId, telephonyManager.getDeviceId());
}
@Test
public void shouldGiveNetworkOperatorName() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkOperatorName("SomeOperatorName");
assertEquals("SomeOperatorName", telephonyManager.getNetworkOperatorName());
}
@Test
public void shouldGiveSimOperatorName() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setSimOperatorName("SomeSimOperatorName");
assertEquals("SomeSimOperatorName", telephonyManager.getSimOperatorName());
}
@Test
public void shouldGiveNetworkType() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkType(TelephonyManager.NETWORK_TYPE_CDMA);
assertEquals(TelephonyManager.NETWORK_TYPE_CDMA, telephonyManager.getNetworkType());
}
@Test @Config(sdk = 17)
public void shouldGiveAllCellInfo() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
ArrayList<CellInfo> allCellInfo = new ArrayList<CellInfo>();
shadowTelephonyManager.setAllCellInfo(allCellInfo);
assertEquals(allCellInfo, telephonyManager.getAllCellInfo());
}
@Test
public void shouldGiveNetworkCountryIso() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkCountryIso("SomeIso");
assertEquals("SomeIso", telephonyManager.getNetworkCountryIso());
}
@Test
public void shouldGiveNetworkOperator() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkOperator("SomeOperator");
assertEquals("SomeOperator", telephonyManager.getNetworkOperator());
}
@Test
public void shouldGiveLine1Number() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setLine1Number("123-244-2222");
assertEquals("123-244-2222", telephonyManager.getLine1Number());
}
@Test
public void shouldGiveGroupIdLevel1() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setGroupIdLevel1("SomeGroupId");
assertEquals("SomeGroupId", telephonyManager.getGroupIdLevel1());
}
@Test(expected = SecurityException.class)
public void getDeviceId_shouldThrowSecurityExceptionWhenReadPhoneStatePermissionNotGranted() throws Exception {
shadowManager.setReadPhoneStatePermission(false);
manager.getDeviceId();
}
@Test
public void shouldGivePhoneType() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setPhoneType( TelephonyManager.PHONE_TYPE_CDMA );
assertEquals(TelephonyManager.PHONE_TYPE_CDMA, telephonyManager.getPhoneType());
shadowTelephonyManager.setPhoneType( TelephonyManager.PHONE_TYPE_GSM );
assertEquals(TelephonyManager.PHONE_TYPE_GSM, telephonyManager.getPhoneType());
}
@Test
public void shouldGiveCellLocation() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
assertThat(telephonyManager.getCellLocation()).isNull();
CellLocation mockCellLocation = mock(CellLocation.class);
shadowOf(telephonyManager).setCellLocation(mockCellLocation);
assertThat(telephonyManager.getCellLocation()).isEqualTo(mockCellLocation);
}
private class MyPhoneStateListener extends PhoneStateListener {
}
}
|
robolectric/src/test/java/org/robolectric/shadows/ShadowTelephonyManagerTest.java
|
package org.robolectric.shadows;
import android.telephony.CellLocation;
import android.telephony.CellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.TestRunners;
import static android.content.Context.TELEPHONY_SERVICE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.robolectric.RuntimeEnvironment.*;
import static org.robolectric.Shadows.shadowOf;
import static org.robolectric.internal.Shadow.newInstanceOf;
@RunWith(TestRunners.MultiApiWithDefaults.class)
public class ShadowTelephonyManagerTest {
private TelephonyManager manager;
private ShadowTelephonyManager shadowManager;
private MyPhoneStateListener listener;
@Before
public void setUp() throws Exception {
manager = newInstanceOf(TelephonyManager.class);
shadowManager = shadowOf(manager);
listener = new MyPhoneStateListener();
}
@Test
public void testListen() {
manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
assertThat(shadowManager.getListener()).isNotNull();
assertThat((MyPhoneStateListener) shadowManager.getListener()).isSameAs(listener);
assertThat(shadowManager.getEventFlags()).isEqualTo(PhoneStateListener.LISTEN_CALL_STATE);
}
@Test
public void shouldGiveDeviceId() {
String testId = "TESTING123";
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
shadowOf(telephonyManager).setDeviceId(testId);
assertEquals(testId, telephonyManager.getDeviceId());
}
@Test
public void shouldGiveNetworkOperatorName() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkOperatorName("SomeOperatorName");
assertEquals("SomeOperatorName", telephonyManager.getNetworkOperatorName());
}
@Test
public void shouldGiveSimOperatorName() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setSimOperatorName("SomeSimOperatorName");
assertEquals("SomeSimOperatorName", telephonyManager.getSimOperatorName());
}
@Test
public void shouldGiveNetworkType() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkType(TelephonyManager.NETWORK_TYPE_CDMA);
assertEquals(TelephonyManager.NETWORK_TYPE_CDMA, telephonyManager.getNetworkType());
}
@Test @Config(sdk = 17)
public void shouldGiveAllCellInfo() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
ArrayList<CellInfo> allCellInfo = new ArrayList<CellInfo>();
shadowTelephonyManager.setAllCellInfo(allCellInfo);
assertEquals(allCellInfo, telephonyManager.getAllCellInfo());
}
@Test
public void shouldGiveNetworkCountryIso() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkCountryIso("SomeIso");
assertEquals("SomeIso", telephonyManager.getNetworkCountryIso());
}
@Test
public void shouldGiveNetworkOperator() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setNetworkOperator("SomeOperator");
assertEquals("SomeOperator", telephonyManager.getNetworkOperator());
}
@Test
public void shouldGiveLine1Number() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setLine1Number("123-244-2222");
assertEquals("123-244-2222", telephonyManager.getLine1Number());
}
@Test(expected = SecurityException.class)
public void getDeviceId_shouldThrowSecurityExceptionWhenReadPhoneStatePermissionNotGranted() throws Exception {
shadowManager.setReadPhoneStatePermission(false);
manager.getDeviceId();
}
@Test
public void shouldGivePhoneType() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
shadowTelephonyManager.setPhoneType( TelephonyManager.PHONE_TYPE_CDMA );
assertEquals(TelephonyManager.PHONE_TYPE_CDMA, telephonyManager.getPhoneType());
shadowTelephonyManager.setPhoneType( TelephonyManager.PHONE_TYPE_GSM );
assertEquals(TelephonyManager.PHONE_TYPE_GSM, telephonyManager.getPhoneType());
}
@Test
public void shouldGiveCellLocation() {
TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
assertThat(telephonyManager.getCellLocation()).isNull();
CellLocation mockCellLocation = mock(CellLocation.class);
shadowOf(telephonyManager).setCellLocation(mockCellLocation);
assertThat(telephonyManager.getCellLocation()).isEqualTo(mockCellLocation);
}
private class MyPhoneStateListener extends PhoneStateListener {
}
}
|
Added test for ShadowTelephonyManager
|
robolectric/src/test/java/org/robolectric/shadows/ShadowTelephonyManagerTest.java
|
Added test for ShadowTelephonyManager
|
<ide><path>obolectric/src/test/java/org/robolectric/shadows/ShadowTelephonyManagerTest.java
<ide> assertEquals("123-244-2222", telephonyManager.getLine1Number());
<ide> }
<ide>
<add> @Test
<add> public void shouldGiveGroupIdLevel1() {
<add> TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
<add> ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
<add> shadowTelephonyManager.setGroupIdLevel1("SomeGroupId");
<add> assertEquals("SomeGroupId", telephonyManager.getGroupIdLevel1());
<add> }
<add>
<ide> @Test(expected = SecurityException.class)
<ide> public void getDeviceId_shouldThrowSecurityExceptionWhenReadPhoneStatePermissionNotGranted() throws Exception {
<ide> shadowManager.setReadPhoneStatePermission(false);
|
|
JavaScript
|
mit
|
19939e00cbd61994daba2d5142afeaaef5e6f8f9
| 0 |
piersroberts/PitchDetect,piersroberts/PitchDetect
|
/*
The MIT License (MIT)
Copyright (c) 2014 Chris Wilson
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.
*/
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = null;
var isPlaying = false;
var sourceNode = null;
var analyser = null;
var theBuffer = null;
var mediaStreamSource = null;
var detectorElem,
waveCanvas,
pitchElem,
noteElem,
detuneElem,
detuneAmount;
var rafID = null;
var tracks = null;
var buflen = 1024;
var buf = new Float32Array( buflen );
var noteStrings = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
var MIN_SAMPLES = 0; // will be initialized when AudioContext is created.
window.onload = function() {
audioContext = new AudioContext();
MAX_SIZE = Math.max(4,Math.floor(audioContext.sampleRate/5000)); // corresponds to a 5kHz signal
var request = new XMLHttpRequest();
request.open("GET", "../sounds/whistling3.ogg", true);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData( request.response, function(buffer) {
theBuffer = buffer;
} );
}
request.send();
detectorElem = document.getElementById( "detector" );
pitchElem = document.getElementById( "pitch" );
noteElem = document.getElementById( "note" );
detuneElem = document.getElementById( "detune" );
detuneAmount = document.getElementById( "detune_amt" );
detectorElem.ondragenter = function () {
this.classList.add("droptarget");
return false; };
detectorElem.ondragleave = function () { this.classList.remove("droptarget"); return false; };
detectorElem.ondrop = function (e) {
this.classList.remove("droptarget");
e.preventDefault();
theBuffer = null;
var reader = new FileReader();
reader.onload = function (event) {
audioContext.decodeAudioData( event.target.result, function(buffer) {
theBuffer = buffer;
}, function(){alert("error loading!");} );
};
reader.onerror = function (event) {
alert("Error: " + reader.error );
};
reader.readAsArrayBuffer(e.dataTransfer.files[0]);
return false;
};
}
function error() {
alert('Stream generation failed.');
}
function getUserMedia(dictionary, callback) {
try {
navigator.getUserMedia =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
navigator.getUserMedia(dictionary, callback, error);
} catch (e) {
alert('getUserMedia threw exception :' + e);
}
}
function gotStream(stream) {
// Create an AudioNode from the stream.
mediaStreamSource = audioContext.createMediaStreamSource(stream);
// Connect it to the destination.
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
mediaStreamSource.connect( analyser );
updatePitch();
}
function toggleLiveInput() {
if (isPlaying) {
//stop playing and return
sourceNode.stop( 0 );
sourceNode = null;
analyser = null;
isPlaying = false;
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
window.cancelAnimationFrame( rafID );
}
getUserMedia(
{
"audio": {
"mandatory": {
"googEchoCancellation": "false",
"googAutoGainControl": "false",
"googNoiseSuppression": "false",
"googHighpassFilter": "false"
},
"optional": []
},
}, gotStream);
}
function togglePlayback() {
if (isPlaying) {
//stop playing and return
sourceNode.stop( 0 );
sourceNode = null;
analyser = null;
isPlaying = false;
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
window.cancelAnimationFrame( rafID );
return "start";
}
sourceNode = audioContext.createBufferSource();
sourceNode.buffer = theBuffer;
sourceNode.loop = true;
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
sourceNode.connect( analyser );
analyser.connect( audioContext.destination );
sourceNode.start( 0 );
isPlaying = true;
isLiveInput = false;
updatePitch();
return "stop";
}
function noteFromPitch( frequency ) {
var noteNum = 12 * (Math.log( frequency / 440 )/Math.log(2) );
return Math.round( noteNum ) + 69;
}
function frequencyFromNoteNumber( note ) {
return 440 * Math.pow(2,(note-69)/12);
}
function centsOffFromPitch( frequency, note ) {
return Math.floor( 1200 * Math.log( frequency / frequencyFromNoteNumber( note ))/Math.log(2) );
}
function autoCorrelate( buf, sampleRate ) {
var SIZE = buf.length;
var MAX_SAMPLES = Math.floor(SIZE/2);
var best_offset = -1;
var best_correlation = 0;
var rms = 0;
var foundGoodCorrelation = false;
var correlations = new Array(MAX_SAMPLES);
for (var i=0;i<SIZE;i++) {
var val = buf[i];
rms += val*val;
}
rms = Math.sqrt(rms/SIZE);
if (rms<0.01) // not enough signal
return -1;
var lastCorrelation=1;
for (var offset = MIN_SAMPLES; offset < MAX_SAMPLES; offset++) {
var correlation = 0;
for (var i=0; i<MAX_SAMPLES; i++) {
correlation += Math.abs((buf[i])-(buf[i+offset]));
}
correlation = 1 - (correlation/MAX_SAMPLES);
correlations[offset] = correlation; // store it, for the tweaking we need to do below.
if ((correlation>0.9) && (correlation > lastCorrelation)) {
foundGoodCorrelation = true;
if (correlation > best_correlation) {
best_correlation = correlation;
best_offset = offset;
}
} else if (foundGoodCorrelation) {
// short-circuit - we found a good correlation, then a bad one, so we'd just be seeing copies from here.
// Now we need to tweak the offset - by interpolating between the values to the left and right of the
// best offset, and shifting it a bit. This is complex, and HACKY in this code (happy to take PRs!) -
// we need to do a curve fit on correlations[] around best_offset in order to better determine precise
// (anti-aliased) offset.
// we know best_offset >=1,
// since foundGoodCorrelation cannot go to true until the second pass (offset=1), and
// we can't drop into this clause until the following pass (else if).
var shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset];
return sampleRate/(best_offset+(8*shift));
}
lastCorrelation = correlation;
}
if (best_correlation > 0.01) {
// console.log("f = " + sampleRate/best_offset + "Hz (rms: " + rms + " confidence: " + best_correlation + ")")
return sampleRate/best_offset;
}
return -1;
// var best_frequency = sampleRate/best_offset;
}
function updatePitch( time ) {
var cycles = new Array;
analyser.getFloatTimeDomainData( buf );
var ac = autoCorrelate( buf, audioContext.sampleRate );
if (ac == -1) {
detectorElem.className = "vague";
pitchElem.innerText = "--";
noteElem.innerText = "-";
detuneElem.className = "";
detuneAmount.innerText = "--";
} else {
detectorElem.className = "confident";
pitch = ac;
pitchElem.innerText = Math.round( pitch ) ;
var note = noteFromPitch( pitch );
noteElem.innerHTML = noteStrings[note%12];
var detune = centsOffFromPitch( pitch, note );
if (detune == 0 ) {
detuneElem.className = "";
detuneAmount.innerHTML = "--";
} else {
if (detune < 0)
detuneElem.className = "flat";
else
detuneElem.className = "sharp";
detuneAmount.innerHTML = Math.abs( detune );
}
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = window.webkitRequestAnimationFrame;
rafID = window.requestAnimationFrame( updatePitch );
}
|
js/pitchdetect.js
|
/*
The MIT License (MIT)
Copyright (c) 2014 Chris Wilson
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.
*/
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = null;
var isPlaying = false;
var sourceNode = null;
var analyser = null;
var theBuffer = null;
var DEBUGCANVAS = null;
var mediaStreamSource = null;
var detectorElem,
canvasElem,
waveCanvas,
pitchElem,
noteElem,
detuneElem,
detuneAmount;
window.onload = function() {
audioContext = new AudioContext();
MAX_SIZE = Math.max(4,Math.floor(audioContext.sampleRate/5000)); // corresponds to a 5kHz signal
var request = new XMLHttpRequest();
request.open("GET", "../sounds/whistling3.ogg", true);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData( request.response, function(buffer) {
theBuffer = buffer;
} );
}
request.send();
detectorElem = document.getElementById( "detector" );
canvasElem = document.getElementById( "output" );
DEBUGCANVAS = document.getElementById( "waveform" );
if (DEBUGCANVAS) {
waveCanvas = DEBUGCANVAS.getContext("2d");
waveCanvas.strokeStyle = "black";
waveCanvas.lineWidth = 1;
}
pitchElem = document.getElementById( "pitch" );
noteElem = document.getElementById( "note" );
detuneElem = document.getElementById( "detune" );
detuneAmount = document.getElementById( "detune_amt" );
detectorElem.ondragenter = function () {
this.classList.add("droptarget");
return false; };
detectorElem.ondragleave = function () { this.classList.remove("droptarget"); return false; };
detectorElem.ondrop = function (e) {
this.classList.remove("droptarget");
e.preventDefault();
theBuffer = null;
var reader = new FileReader();
reader.onload = function (event) {
audioContext.decodeAudioData( event.target.result, function(buffer) {
theBuffer = buffer;
}, function(){alert("error loading!");} );
};
reader.onerror = function (event) {
alert("Error: " + reader.error );
};
reader.readAsArrayBuffer(e.dataTransfer.files[0]);
return false;
};
}
function error() {
alert('Stream generation failed.');
}
function getUserMedia(dictionary, callback) {
try {
navigator.getUserMedia =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
navigator.getUserMedia(dictionary, callback, error);
} catch (e) {
alert('getUserMedia threw exception :' + e);
}
}
function gotStream(stream) {
// Create an AudioNode from the stream.
mediaStreamSource = audioContext.createMediaStreamSource(stream);
// Connect it to the destination.
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
mediaStreamSource.connect( analyser );
updatePitch();
}
function toggleOscillator() {
if (isPlaying) {
//stop playing and return
sourceNode.stop( 0 );
sourceNode = null;
analyser = null;
isPlaying = false;
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
window.cancelAnimationFrame( rafID );
return "play oscillator";
}
sourceNode = audioContext.createOscillator();
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
sourceNode.connect( analyser );
analyser.connect( audioContext.destination );
sourceNode.start(0);
isPlaying = true;
isLiveInput = false;
updatePitch();
return "stop";
}
function toggleLiveInput() {
if (isPlaying) {
//stop playing and return
sourceNode.stop( 0 );
sourceNode = null;
analyser = null;
isPlaying = false;
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
window.cancelAnimationFrame( rafID );
}
getUserMedia(
{
"audio": {
"mandatory": {
"googEchoCancellation": "false",
"googAutoGainControl": "false",
"googNoiseSuppression": "false",
"googHighpassFilter": "false"
},
"optional": []
},
}, gotStream);
}
function togglePlayback() {
if (isPlaying) {
//stop playing and return
sourceNode.stop( 0 );
sourceNode = null;
analyser = null;
isPlaying = false;
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
window.cancelAnimationFrame( rafID );
return "start";
}
sourceNode = audioContext.createBufferSource();
sourceNode.buffer = theBuffer;
sourceNode.loop = true;
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
sourceNode.connect( analyser );
analyser.connect( audioContext.destination );
sourceNode.start( 0 );
isPlaying = true;
isLiveInput = false;
updatePitch();
return "stop";
}
var rafID = null;
var tracks = null;
var buflen = 1024;
var buf = new Float32Array( buflen );
var noteStrings = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
function noteFromPitch( frequency ) {
var noteNum = 12 * (Math.log( frequency / 440 )/Math.log(2) );
return Math.round( noteNum ) + 69;
}
function frequencyFromNoteNumber( note ) {
return 440 * Math.pow(2,(note-69)/12);
}
function centsOffFromPitch( frequency, note ) {
return Math.floor( 1200 * Math.log( frequency / frequencyFromNoteNumber( note ))/Math.log(2) );
}
// this is a float version of the algorithm below - but it's not currently used.
/*
function autoCorrelateFloat( buf, sampleRate ) {
var MIN_SAMPLES = 4; // corresponds to an 11kHz signal
var MAX_SAMPLES = 1000; // corresponds to a 44Hz signal
var SIZE = 1000;
var best_offset = -1;
var best_correlation = 0;
var rms = 0;
if (buf.length < (SIZE + MAX_SAMPLES - MIN_SAMPLES))
return -1; // Not enough data
for (var i=0;i<SIZE;i++)
rms += buf[i]*buf[i];
rms = Math.sqrt(rms/SIZE);
for (var offset = MIN_SAMPLES; offset <= MAX_SAMPLES; offset++) {
var correlation = 0;
for (var i=0; i<SIZE; i++) {
correlation += Math.abs(buf[i]-buf[i+offset]);
}
correlation = 1 - (correlation/SIZE);
if (correlation > best_correlation) {
best_correlation = correlation;
best_offset = offset;
}
}
if ((rms>0.1)&&(best_correlation > 0.1)) {
console.log("f = " + sampleRate/best_offset + "Hz (rms: " + rms + " confidence: " + best_correlation + ")");
}
// var best_frequency = sampleRate/best_offset;
}
*/
var MIN_SAMPLES = 0; // will be initialized when AudioContext is created.
function autoCorrelate( buf, sampleRate ) {
var SIZE = buf.length;
var MAX_SAMPLES = Math.floor(SIZE/2);
var best_offset = -1;
var best_correlation = 0;
var rms = 0;
var foundGoodCorrelation = false;
var correlations = new Array(MAX_SAMPLES);
for (var i=0;i<SIZE;i++) {
var val = buf[i];
rms += val*val;
}
rms = Math.sqrt(rms/SIZE);
if (rms<0.01) // not enough signal
return -1;
var lastCorrelation=1;
for (var offset = MIN_SAMPLES; offset < MAX_SAMPLES; offset++) {
var correlation = 0;
for (var i=0; i<MAX_SAMPLES; i++) {
correlation += Math.abs((buf[i])-(buf[i+offset]));
}
correlation = 1 - (correlation/MAX_SAMPLES);
correlations[offset] = correlation; // store it, for the tweaking we need to do below.
if ((correlation>0.9) && (correlation > lastCorrelation)) {
foundGoodCorrelation = true;
if (correlation > best_correlation) {
best_correlation = correlation;
best_offset = offset;
}
} else if (foundGoodCorrelation) {
// short-circuit - we found a good correlation, then a bad one, so we'd just be seeing copies from here.
// Now we need to tweak the offset - by interpolating between the values to the left and right of the
// best offset, and shifting it a bit. This is complex, and HACKY in this code (happy to take PRs!) -
// we need to do a curve fit on correlations[] around best_offset in order to better determine precise
// (anti-aliased) offset.
// we know best_offset >=1,
// since foundGoodCorrelation cannot go to true until the second pass (offset=1), and
// we can't drop into this clause until the following pass (else if).
var shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset];
return sampleRate/(best_offset+(8*shift));
}
lastCorrelation = correlation;
}
if (best_correlation > 0.01) {
// console.log("f = " + sampleRate/best_offset + "Hz (rms: " + rms + " confidence: " + best_correlation + ")")
return sampleRate/best_offset;
}
return -1;
// var best_frequency = sampleRate/best_offset;
}
function updatePitch( time ) {
var cycles = new Array;
analyser.getFloatTimeDomainData( buf );
var ac = autoCorrelate( buf, audioContext.sampleRate );
// TODO: Paint confidence meter on canvasElem here.
if (DEBUGCANVAS) { // This draws the current waveform, useful for debugging
waveCanvas.clearRect(0,0,512,256);
waveCanvas.strokeStyle = "red";
waveCanvas.beginPath();
waveCanvas.moveTo(0,0);
waveCanvas.lineTo(0,256);
waveCanvas.moveTo(128,0);
waveCanvas.lineTo(128,256);
waveCanvas.moveTo(256,0);
waveCanvas.lineTo(256,256);
waveCanvas.moveTo(384,0);
waveCanvas.lineTo(384,256);
waveCanvas.moveTo(512,0);
waveCanvas.lineTo(512,256);
waveCanvas.stroke();
waveCanvas.strokeStyle = "black";
waveCanvas.beginPath();
waveCanvas.moveTo(0,buf[0]);
for (var i=1;i<512;i++) {
waveCanvas.lineTo(i,128+(buf[i]*128));
}
waveCanvas.stroke();
}
if (ac == -1) {
detectorElem.className = "vague";
pitchElem.innerText = "--";
noteElem.innerText = "-";
detuneElem.className = "";
detuneAmount.innerText = "--";
} else {
detectorElem.className = "confident";
pitch = ac;
pitchElem.innerText = Math.round( pitch ) ;
var note = noteFromPitch( pitch );
noteElem.innerHTML = noteStrings[note%12];
var detune = centsOffFromPitch( pitch, note );
if (detune == 0 ) {
detuneElem.className = "";
detuneAmount.innerHTML = "--";
} else {
if (detune < 0)
detuneElem.className = "flat";
else
detuneElem.className = "sharp";
detuneAmount.innerHTML = Math.abs( detune );
}
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = window.webkitRequestAnimationFrame;
rafID = window.requestAnimationFrame( updatePitch );
}
|
removed some crud
|
js/pitchdetect.js
|
removed some crud
|
<ide><path>s/pitchdetect.js
<ide> var sourceNode = null;
<ide> var analyser = null;
<ide> var theBuffer = null;
<del>var DEBUGCANVAS = null;
<ide> var mediaStreamSource = null;
<ide> var detectorElem,
<del> canvasElem,
<ide> waveCanvas,
<ide> pitchElem,
<ide> noteElem,
<ide> detuneElem,
<ide> detuneAmount;
<add>
<add>
<add>var rafID = null;
<add>var tracks = null;
<add>var buflen = 1024;
<add>var buf = new Float32Array( buflen );
<add>var noteStrings = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
<add>var MIN_SAMPLES = 0; // will be initialized when AudioContext is created.
<ide>
<ide> window.onload = function() {
<ide> audioContext = new AudioContext();
<ide> request.send();
<ide>
<ide> detectorElem = document.getElementById( "detector" );
<del> canvasElem = document.getElementById( "output" );
<del> DEBUGCANVAS = document.getElementById( "waveform" );
<del> if (DEBUGCANVAS) {
<del> waveCanvas = DEBUGCANVAS.getContext("2d");
<del> waveCanvas.strokeStyle = "black";
<del> waveCanvas.lineWidth = 1;
<del> }
<add>
<ide> pitchElem = document.getElementById( "pitch" );
<ide> noteElem = document.getElementById( "note" );
<ide> detuneElem = document.getElementById( "detune" );
<ide> reader.readAsArrayBuffer(e.dataTransfer.files[0]);
<ide> return false;
<ide> };
<del>
<del>
<del>
<ide> }
<ide>
<ide> function error() {
<ide> updatePitch();
<ide> }
<ide>
<del>function toggleOscillator() {
<del> if (isPlaying) {
<del> //stop playing and return
<del> sourceNode.stop( 0 );
<del> sourceNode = null;
<del> analyser = null;
<del> isPlaying = false;
<del> if (!window.cancelAnimationFrame)
<del> window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
<del> window.cancelAnimationFrame( rafID );
<del> return "play oscillator";
<del> }
<del> sourceNode = audioContext.createOscillator();
<del>
<del> analyser = audioContext.createAnalyser();
<del> analyser.fftSize = 2048;
<del> sourceNode.connect( analyser );
<del> analyser.connect( audioContext.destination );
<del> sourceNode.start(0);
<del> isPlaying = true;
<del> isLiveInput = false;
<del> updatePitch();
<del>
<del> return "stop";
<del>}
<ide>
<ide> function toggleLiveInput() {
<ide> if (isPlaying) {
<ide> return "stop";
<ide> }
<ide>
<del>var rafID = null;
<del>var tracks = null;
<del>var buflen = 1024;
<del>var buf = new Float32Array( buflen );
<del>
<del>var noteStrings = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
<del>
<ide> function noteFromPitch( frequency ) {
<ide> var noteNum = 12 * (Math.log( frequency / 440 )/Math.log(2) );
<ide> return Math.round( noteNum ) + 69;
<ide> function centsOffFromPitch( frequency, note ) {
<ide> return Math.floor( 1200 * Math.log( frequency / frequencyFromNoteNumber( note ))/Math.log(2) );
<ide> }
<del>
<del>// this is a float version of the algorithm below - but it's not currently used.
<del>/*
<del>function autoCorrelateFloat( buf, sampleRate ) {
<del> var MIN_SAMPLES = 4; // corresponds to an 11kHz signal
<del> var MAX_SAMPLES = 1000; // corresponds to a 44Hz signal
<del> var SIZE = 1000;
<del> var best_offset = -1;
<del> var best_correlation = 0;
<del> var rms = 0;
<del>
<del> if (buf.length < (SIZE + MAX_SAMPLES - MIN_SAMPLES))
<del> return -1; // Not enough data
<del>
<del> for (var i=0;i<SIZE;i++)
<del> rms += buf[i]*buf[i];
<del> rms = Math.sqrt(rms/SIZE);
<del>
<del> for (var offset = MIN_SAMPLES; offset <= MAX_SAMPLES; offset++) {
<del> var correlation = 0;
<del>
<del> for (var i=0; i<SIZE; i++) {
<del> correlation += Math.abs(buf[i]-buf[i+offset]);
<del> }
<del> correlation = 1 - (correlation/SIZE);
<del> if (correlation > best_correlation) {
<del> best_correlation = correlation;
<del> best_offset = offset;
<del> }
<del> }
<del> if ((rms>0.1)&&(best_correlation > 0.1)) {
<del> console.log("f = " + sampleRate/best_offset + "Hz (rms: " + rms + " confidence: " + best_correlation + ")");
<del> }
<del>// var best_frequency = sampleRate/best_offset;
<del>}
<del>*/
<del>
<del>var MIN_SAMPLES = 0; // will be initialized when AudioContext is created.
<ide>
<ide> function autoCorrelate( buf, sampleRate ) {
<ide> var SIZE = buf.length;
<ide> var cycles = new Array;
<ide> analyser.getFloatTimeDomainData( buf );
<ide> var ac = autoCorrelate( buf, audioContext.sampleRate );
<del> // TODO: Paint confidence meter on canvasElem here.
<del>
<del> if (DEBUGCANVAS) { // This draws the current waveform, useful for debugging
<del> waveCanvas.clearRect(0,0,512,256);
<del> waveCanvas.strokeStyle = "red";
<del> waveCanvas.beginPath();
<del> waveCanvas.moveTo(0,0);
<del> waveCanvas.lineTo(0,256);
<del> waveCanvas.moveTo(128,0);
<del> waveCanvas.lineTo(128,256);
<del> waveCanvas.moveTo(256,0);
<del> waveCanvas.lineTo(256,256);
<del> waveCanvas.moveTo(384,0);
<del> waveCanvas.lineTo(384,256);
<del> waveCanvas.moveTo(512,0);
<del> waveCanvas.lineTo(512,256);
<del> waveCanvas.stroke();
<del> waveCanvas.strokeStyle = "black";
<del> waveCanvas.beginPath();
<del> waveCanvas.moveTo(0,buf[0]);
<del> for (var i=1;i<512;i++) {
<del> waveCanvas.lineTo(i,128+(buf[i]*128));
<del> }
<del> waveCanvas.stroke();
<del> }
<ide>
<ide> if (ac == -1) {
<ide> detectorElem.className = "vague";
|
|
Java
|
bsd-3-clause
|
a19847db4d466734c58ca007d39350908abc4b75
| 0 |
srujun/Zeke-Java,TheGreenMachine/Zeke-Java
|
package com.edinarobotics.zeke.vision;
import com.edinarobotics.utils.log.Level;
import com.edinarobotics.utils.log.LogSystem;
import com.edinarobotics.utils.log.Logger;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
/**
*
* @author GreenMachine
*/
public class VisionConnectThread extends Thread {
private int port;
private Logger logger;
private volatile boolean stop;
private VisionServer server;
private VisionReadingThread currentReadingThread;
public VisionConnectThread(int port, VisionServer server) {
this.port = port;
this.logger = LogSystem.getLogger("zeke.vision.conn");
stop = false;
this.server = server;
}
public void requestStop() {
this.stop = true;
if (currentReadingThread != null) {
currentReadingThread.requestStop();
}
}
public VisionReadingThread getReadingThread() {
return currentReadingThread;
}
public void run() {
ServerSocketConnection serverSocket = null;
try {
serverSocket = (ServerSocketConnection) Connector.open("socket://:"+port);
while (!stop) {
try {
if (currentReadingThread != null && currentReadingThread.isAlive()) {
currentReadingThread.join();
}
SocketConnection connection = (SocketConnection) serverSocket.acceptAndOpen();
currentReadingThread = new VisionReadingThread(connection, server);
currentReadingThread.start();
Thread.sleep(100);
} catch (InterruptedException e) {
logger.log(Level.INFO, "Vision connect thread interrupted.");
e.printStackTrace();
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to receive new connections.");
e.printStackTrace();
} finally {
// Close the server socket if we need to.
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
logger.log(Level.SEVERE, "Failed to close server socket.");
}
}
}
logger.log(Level.INFO, "Vision connect thread exited.");
}
}
|
src/com/edinarobotics/zeke/vision/VisionConnectThread.java
|
package com.edinarobotics.zeke.vision;
import com.edinarobotics.utils.log.Level;
import com.edinarobotics.utils.log.LogSystem;
import com.edinarobotics.utils.log.Logger;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
/**
*
* @author GreenMachine
*/
public class VisionConnectThread extends Thread {
private int port;
private Logger logger;
private volatile boolean stop;
private VisionServer server;
private VisionReadingThread currentReadingThread;
public VisionConnectThread(int port, VisionServer server) {
this.port = port;
this.logger = LogSystem.getLogger("zeke.vision.conn");
stop = false;
this.server = server;
}
public void requestStop() {
this.stop = true;
if (currentReadingThread != null) {
currentReadingThread.requestStop();
}
}
public VisionReadingThread getReadingThread() {
return currentReadingThread;
}
public void run() {
ServerSocketConnection serverSocket = null;
try {
serverSocket = (ServerSocketConnection) Connector.open("serversocket:///:"+port);
while (!stop) {
try {
if (currentReadingThread != null && currentReadingThread.isAlive()) {
currentReadingThread.join();
}
SocketConnection connection = (SocketConnection) serverSocket.acceptAndOpen();
currentReadingThread = new VisionReadingThread(connection, server);
currentReadingThread.start();
Thread.sleep(100);
} catch (InterruptedException e) {
logger.log(Level.INFO, "Vision connect thread interrupted.");
e.printStackTrace();
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to receive new connections.");
e.printStackTrace();
} finally {
// Close the server socket if we need to.
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
logger.log(Level.SEVERE, "Failed to close server socket.");
}
}
}
logger.log(Level.INFO, "Vision connect thread exited.");
}
}
|
Change connection string in VisionConnectThread to create the socket.
|
src/com/edinarobotics/zeke/vision/VisionConnectThread.java
|
Change connection string in VisionConnectThread to create the socket.
|
<ide><path>rc/com/edinarobotics/zeke/vision/VisionConnectThread.java
<ide> public void run() {
<ide> ServerSocketConnection serverSocket = null;
<ide> try {
<del> serverSocket = (ServerSocketConnection) Connector.open("serversocket:///:"+port);
<add> serverSocket = (ServerSocketConnection) Connector.open("socket://:"+port);
<ide> while (!stop) {
<ide> try {
<ide> if (currentReadingThread != null && currentReadingThread.isAlive()) {
|
|
Java
|
apache-2.0
|
1c29beb711149e95be17d3f910b312fcdc7804e1
| 0 |
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
|
package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.exceptions.CMException;
import com.planet_ink.coffee_mud.core.exceptions.MQLException;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.Area.State;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutNode;
import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary.XMLTag;
import com.planet_ink.coffee_mud.Libraries.interfaces.AbilityMapper.AbilityMapping;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.io.*;
/*
Copyright 2008-2019 Bo Zimmerman
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.
*/
public class MUDPercolator extends StdLibrary implements AreaGenerationLibrary
{
@Override
public String ID()
{
return "MUDPercolator";
}
protected final static char[] splitters=new char[]{'<','>','='};
protected final static Triad<Integer,Integer,Class<?>[]> emptyMetacraftFilter = new Triad<Integer,Integer,Class<?>[]>(Integer.valueOf(-1),Integer.valueOf(-1),new Class<?>[0]);
protected final static String POST_PROCESSING_STAT_SETS="___POST_PROCESSING_SETS___";
protected final static Set<String> UPPER_REQUIRES_KEYWORDS=new XHashSet<String>(new String[]{"INT","INTEGER","$","STRING","ANY","DOUBLE","#","NUMBER"});
protected final static CMParms.DelimiterChecker REQUIRES_DELIMITERS=CMParms.createDelimiter(new char[]{' ','\t',',','\r','\n'});
private final SHashtable<String,Class<LayoutManager>> mgrs = new SHashtable<String,Class<LayoutManager>>();
private interface BuildCallback
{
public void willBuild(Environmental E, XMLTag XMLTag);
}
private static final Filterer<MOB> noMobFilter = new Filterer<MOB>()
{
@Override
public boolean passesFilter(final MOB obj)
{
return (obj != null) && (CMLib.flags().isInTheGame(obj, true));
}
};
private static final Filterer<MOB> npcFilter = new Filterer<MOB>()
{
@Override
public boolean passesFilter(final MOB obj)
{
return (obj != null)
&& (!obj.isPlayer())
&&((obj.amFollowing()==null)||(!obj.amUltimatelyFollowing().isPlayer()));
}
};
private static final Converter<Session, MOB> sessionToMobConvereter= new Converter<Session, MOB>()
{
@Override
public MOB convert(final Session obj)
{
// TODO Auto-generated method stub
return null;
}
};
private static final Comparator<Object> objComparator = new Comparator<Object>()
{
@Override
public int compare(final Object o1, final Object o2)
{
final String s1=(o1 instanceof Environmental)?((Environmental)o1).Name():(o1==null?"":o1.toString());
final String s2=(o1 instanceof Environmental)?((Environmental)o2).Name():(o2==null?"":o2.toString());
if(CMath.isNumber(s1) && CMath.isNumber(s2))
{
final double d1=CMath.s_double(s1);
final double d2=CMath.s_double(s2);
return (d1==d2)?0:(d1>d2?1:-1);
}
return s1.compareToIgnoreCase(s2);
}
};
@Override
public LayoutManager getLayoutManager(final String named)
{
final Class<LayoutManager> mgr = mgrs.get(named.toUpperCase().trim());
if(mgr != null)
{
try
{
return mgr.newInstance();
}
catch(final Exception e)
{
return null;
}
}
return null;
}
@Override
public void buildDefinedIDSet(final List<XMLTag> xmlRoot, final Map<String,Object> defined)
{
if(xmlRoot==null)
return;
for(int v=0;v<xmlRoot.size();v++)
{
final XMLLibrary.XMLTag piece = xmlRoot.get(v);
final String id = piece.getParmValue("ID");
if((id!=null)&&(id.length()>0))
{
final Object o=defined.get(id.toUpperCase());
if(o != null)
{
if(!(o instanceof XMLTag))
Log.errOut("Duplicate ID: "+id+" (first tag did not resolve to a complex piece -- it wins.)");
else
{
final Boolean pMergeVal;
if((piece.parms()==null)||(!piece.parms().containsKey("MERGE")))
pMergeVal = null;
else
pMergeVal = Boolean.valueOf(CMath.s_bool(piece.parms().get("MERGE")));
final Boolean oMergeVal;
if((((XMLTag)o).parms()==null)||(!((XMLTag)o).parms().containsKey("MERGE")))
oMergeVal = null;
else
oMergeVal = Boolean.valueOf(CMath.s_bool(((XMLTag)o).parms().get("MERGE")));
if((pMergeVal == null)||(oMergeVal == null))
Log.errOut("Duplicate ID: "+id+" (no MERGE tag found to permit this operation -- first tag wins.)");
else
if(pMergeVal.booleanValue() && oMergeVal.booleanValue())
{
final XMLTag src=piece;
final XMLTag tgt=(XMLTag)o;
if(!src.tag().equalsIgnoreCase(tgt.tag()))
Log.errOut("Unable to merge tags with ID: "+id+", they are of different types.");
else
for(final String parm : src.parms().keySet())
{
final String srcParmVal=src.parms().get(parm);
final String tgtParmVal=tgt.parms().get(parm);
if(tgtParmVal==null)
tgt.parms().put(parm,srcParmVal);
else
if(tgtParmVal.equalsIgnoreCase(srcParmVal)||parm.equalsIgnoreCase("ID"))
{
/* do nothing -- nothing to do */
}
else
if(parm.equalsIgnoreCase("REQUIRES"))
{
final Map<String,String> srcParms=CMParms.parseEQParms(srcParmVal, REQUIRES_DELIMITERS, true);
final Map<String,String> tgtParms=CMParms.parseEQParms(tgtParmVal, REQUIRES_DELIMITERS, true);
for(final String srcKey : srcParms.keySet())
{
final String srcVal=srcParms.get(srcKey);
final String tgtVal=tgtParms.get(srcKey);
if(tgtVal == null)
tgtParms.put(srcKey, srcVal);
else
if(UPPER_REQUIRES_KEYWORDS.contains(srcVal.toUpperCase()))
{
if(!srcVal.equalsIgnoreCase(tgtVal))
Log.errOut("Unable to merge REQUIRES parm on tags with ID: "+id+", mismatch in requirements for '"+srcKey+"'.");
}
else
if(UPPER_REQUIRES_KEYWORDS.contains(tgtVal.toUpperCase()))
Log.errOut("Unable to merge REQUIRES parm on tags with ID: "+id+", mismatch in requirements for '"+srcKey+"'.");
else
tgtParms.put(srcKey,srcVal+";"+tgtVal);
}
tgt.parms().put(parm, CMParms.combineEQParms(tgtParms, ','));
}
else
if(parm.equalsIgnoreCase("CONDITION")||parm.equalsIgnoreCase("VALIDATE"))
tgt.parms().put(parm, tgtParmVal+" and "+srcParmVal);
else
if(parm.equalsIgnoreCase("INSERT")||parm.equalsIgnoreCase("DEFINE")||parm.equalsIgnoreCase("PREDEFINE"))
tgt.parms().put(parm, tgtParmVal+","+srcParmVal);
else
Log.errOut("Unable to merge SELECT parm on tags with ID: "+id+".");
}
for(final XMLLibrary.XMLTag subPiece : src.contents())
{
final Boolean subMergeVal;
if((subPiece.parms()==null)||(!subPiece.parms().containsKey("MERGE")))
subMergeVal = null;
else
subMergeVal = Boolean.valueOf(CMath.s_bool(subPiece.parms().get("MERGE")));
if((subMergeVal == null)||(subMergeVal.booleanValue()))
tgt.contents().add(subPiece);
}
}
}
}
else
defined.put(id.toUpperCase().trim(),piece);
}
final String load = piece.getParmValue("LOAD");
if((load!=null)&&(load.length()>0))
{
piece.parms().remove("LOAD");
XMLTag loadedPiece=(XMLTag)defined.get("SYSTEM_LOADED_XML_FILES");
if(loadedPiece==null)
{
loadedPiece=CMLib.xml().createNewTag("SYSTEM_LOADED_XML_FILES","");
defined.put("SYSTEM_LOADED_XML_FILES", loadedPiece);
}
final CMFile file = new CMFile(load,null,CMFile.FLAG_LOGERRORS|CMFile.FLAG_FORCEALLOW);
if(loadedPiece.getPieceFromPieces( file.getAbsolutePath().toUpperCase())==null)
{
loadedPiece.contents().add(CMLib.xml().createNewTag(file.getAbsolutePath().toUpperCase(),"true"));
if(file.exists() && file.canRead())
{
final List<XMLTag> addPieces=CMLib.xml().parseAllXML(file.text());
piece.contents().addAll(addPieces);
}
}
}
buildDefinedIDSet(piece.contents(),defined);
}
}
//@Override public
void testMQLParsing()
{
final String[] testMQLs = new String[] {
"SELECT: x from y where xxx > ydd and ( yyy<=djj ) or zzz > jkkk",
"SELECT: x from y where xxx > ydd and ttt>3 or ( yyy<=djj ) and zzz > jkkk or 6>7",
"SELECT: x from y",
"SELECT: x, XX from y",
"SELECT: x,xx,xxx from y",
"SELECT: x, xx , xxx from y",
"SELECT: x, xx , xxx from (select: x from y)",
"SELECT: x from y where x>y",
"SELECT: x from y where x >y",
"SELECT: x from y where x> y",
"SELECT: x from y where xxx> ydd and yyy<=djj",
"SELECT: x from y where xxx> ydd and yyy<=djj or zzz > jkkk and rrr>ddd",
"SELECT: x from (select: x from y) where (xxx > ydd) and ( yyy<=djj ) or (zzz > jkkk)and(rrr>ddd)",
"SELECT: x from y where ((xxx > ydd) and ( yyy<=djj )) or((zzz > jkkk)and ((rrr>ddd) or (ddd>888)))",
};
for(int i=0;i<testMQLs.length;i++)
{
final String mqlWSelect=testMQLs[i];
final int x=mqlWSelect.indexOf(':');
final String mql=mqlWSelect.substring(x+1).toUpperCase().trim();
try
{
final MQLClause clause = new MQLClause();
clause.parseMQL(testMQLs[i], mql);
}
catch(final Exception e)
{
System.out.println(e.getMessage());
}
}
}
@Override
@SuppressWarnings("unchecked")
public boolean activate()
{
final String filePath="com/planet_ink/coffee_mud/Libraries/layouts";
final CMProps page = CMProps.instance();
final Vector<Object> layouts=CMClass.loadClassList(filePath,page.getStr("LIBRARY"),"/layouts",LayoutManager.class,true);
for(int f=0;f<layouts.size();f++)
{
final LayoutManager lmgr= (LayoutManager)layouts.elementAt(f);
final Class<LayoutManager> lmgrClass=(Class<LayoutManager>)lmgr.getClass();
mgrs.put(lmgr.name().toUpperCase().trim(),lmgrClass);
}
return true;
}
@Override
public boolean shutdown()
{
mgrs.clear();
return true;
}
private final static class PostProcessException extends Exception
{
private static final long serialVersionUID = -8797769166795010761L;
public PostProcessException(final String s)
{
super(s);
}
}
protected abstract class PostProcessAttempt
{
protected Map<String,Object> defined=null;
protected boolean firstRun=true;
public abstract String attempt() throws CMException,PostProcessException;
}
@SuppressWarnings("unchecked")
protected final String PostProcessAttempter(final Map<String,Object> defined, final PostProcessAttempt attempter) throws CMException
{
try
{
attempter.defined=defined;
final String result = attempter.attempt();
return result;
}
catch(final PostProcessException pe)
{
List<PostProcessAttempt> posties=(List<PostProcessAttempt>)defined.get(MUDPercolator.POST_PROCESSING_STAT_SETS);
if(posties==null)
{
posties=new Vector<PostProcessAttempt>();
defined.put(MUDPercolator.POST_PROCESSING_STAT_SETS, posties);
}
attempter.firstRun=false;
final Map<String,Object> definedCopy;
if(defined instanceof Hashtable)
definedCopy=(Map<String,Object>)((Hashtable<String,Object>)defined).clone();
else
definedCopy=new Hashtable<String,Object>(defined);
attempter.defined=definedCopy;
posties.add(attempter);
return null;
}
}
protected void fillOutRequiredStatCodeSafe(final Modifiable E, final List<String> ignoreStats, final String defPrefix,
final String tagName, final String statName, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String val = findString(E,ignoreStats,defPrefix,tagName,piece,this.defined);
E.setStat(statName, val);
if((defPrefix!=null)&&(defPrefix.length()>0))
addDefinition(defPrefix+tagName,val,defined);
return val;
}
});
}
// vars created: ROOM_CLASS, ROOM_TITLE, ROOM_DESCRIPTION, ROOM_CLASSES, ROOM_TITLES, ROOM_DESCRIPTIONS
@Override
public Room buildRoom(final XMLTag piece, final Map<String,Object> defined, final Exit[] exits, final int direction) throws CMException
{
addDefinition("DIRECTION",CMLib.directions().getDirectionName(direction).toLowerCase(),defined);
final String classID = findStringNow("class",piece,defined);
final Room R = CMClass.getLocale(classID);
if(R == null)
throw new CMException("Unable to build room on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
addDefinition("ROOM_CLASS",classID,defined);
final List<String> ignoreStats=new XArrayList<String>(new String[]{"CLASS","DISPLAY","DESCRIPTION"});
fillOutRequiredStatCodeSafe(R, ignoreStats, "ROOM_", "TITLE", "DISPLAY", piece, defined);
fillOutRequiredStatCodeSafe(R, ignoreStats, "ROOM_", "DESCRIPTION", "DESCRIPTION", piece, defined);
fillOutCopyCodes(R, ignoreStats, "ROOM_", piece, defined);
fillOutStatCodes(R, ignoreStats, "ROOM_", piece, defined);
final List<MOB> mV = findMobs(piece,defined);
for(int i=0;i<mV.size();i++)
{
final MOB M=mV.get(i);
M.setSavable(true);
M.bringToLife(R,true);
}
final List<Item> iV = findItems(piece,defined);
for(int i=0;i<iV.size();i++)
{
final Item I=iV.get(i);
R.addItem(I);
I.setSavable(true);
I.setExpirationDate(0);
}
final List<Ability> aV = findAffects(R,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability A=aV.get(i);
A.setSavable(true);
R.addNonUninvokableEffect(A);
}
final List<Behavior> bV = findBehaviors(R,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
R.addBehavior(B);
}
for(int dir=0;dir<Directions.NUM_DIRECTIONS();dir++)
{
Exit E=exits[dir];
if((E==null)&&(defined.containsKey("ROOMLINK_"+CMLib.directions().getDirectionChar(dir).toUpperCase())))
{
defined.put("ROOMLINK_DIR",CMLib.directions().getDirectionChar(dir).toUpperCase());
final Exit E2=findExit(R,piece, defined);
if(E2!=null)
E=E2;
defined.remove("ROOMLINK_DIR");
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","EXIT:NEW:"+((E==null)?"null":E.ID())+":DIR="+CMLib.directions().getDirectionChar(dir).toUpperCase()+":ROOM="+R.getStat("DISPLAY"));
}
else
if((CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))&&defined.containsKey("ROOMLINK_"+CMLib.directions().getDirectionChar(dir).toUpperCase()))
Log.debugOut("MUDPercolator","EXIT:OLD:"+((E==null)?"null":E.ID())+":DIR="+CMLib.directions().getDirectionChar(dir).toUpperCase()+":ROOM="+R.getStat("DISPLAY"));
R.setRawExit(dir, E);
R.startItemRejuv();
}
return R;
}
@SuppressWarnings("unchecked")
@Override
public void postProcess(final Map<String,Object> defined) throws CMException
{
final List<PostProcessAttempt> posties=(List<PostProcessAttempt>)defined.get(MUDPercolator.POST_PROCESSING_STAT_SETS);
if(posties == null)
return;
try
{
for(final PostProcessAttempt stat : posties)
{
try
{
stat.attempt();
}
catch(final PostProcessException pe)
{
throw pe;
}
}
}
catch(final PostProcessException pe)
{
throw new CMException("Unsatisfied Post Process Exception: "+pe.getMessage(),pe);
}
}
protected void layoutRecursiveFill(final LayoutNode n, final HashSet<LayoutNode> nodesDone, final Vector<LayoutNode> group, final LayoutTypes type)
{
if(n != null)
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
if(n.links().containsKey(Integer.valueOf(d)))
{
final LayoutNode offN=n.links().get(Integer.valueOf(d));
if((offN.type()==type)
&&(!group.contains(offN))
&&(!nodesDone.contains(offN)))
{
group.addElement(offN);
nodesDone.add(offN);
layoutRecursiveFill(offN,nodesDone,group,type);
}
}
}
}
protected void layoutFollow(LayoutNode n, final LayoutTypes type, final int direction, final HashSet<LayoutNode> nodesAlreadyGrouped, final List<LayoutNode> group)
{
n=n.links().get(Integer.valueOf(direction));
while((n != null) &&(n.type()==LayoutTypes.street) &&(!group.contains(n) &&(!nodesAlreadyGrouped.contains(n))))
{
nodesAlreadyGrouped.add(n);
group.add(n);
n=n.links().get(Integer.valueOf(direction));
}
}
@Override
public Area findArea(final XMLTag piece, final Map<String,Object> defined, final int directions) throws CMException
{
try
{
final String tagName="AREA";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
{
return null;
}
while(choices.size()>0)
{
final XMLLibrary.XMLTag valPiece = choices.get(CMLib.dice().roll(1,choices.size(),-1));
choices.remove(valPiece);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(null,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final Map<String,Object> rDefined=new Hashtable<String,Object>();
rDefined.putAll(defined);
defineReward(null,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,rDefined,true);
final Area A=buildArea(valPiece,rDefined,directions);
for (final String key : rDefined.keySet())
{
if(key.startsWith("_"))
defined.put(key,rDefined.get(key));
}
return A;
}
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
return null;
}
protected Area buildArea(final XMLTag piece, final Map<String,Object> defined, final int direction) throws CMException
{
defined.put("DIRECTION",CMLib.directions().getDirectionName(direction).toLowerCase());
final String classID = findStringNow("class",piece,defined);
final Area A = CMClass.getAreaType(classID);
if(A == null)
throw new CMException("Unable to build area on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
defined.put("AREA_CLASS",classID);
final String name = findStringNow(A,null,"AREA_","NAME",piece,defined);
if(CMLib.map().getArea(name)!=null)
{
A.destroy();
throw new CMException("Unable to create area '"+name+"', you must destroy the old one first.");
}
A.setName(name);
defined.put("AREA_NAME",name);
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String author = findOptionalString(A,null,"AREA_","author",piece,this.defined, false);
if(author != null)
{
A.setAuthorID(author);
defined.put("AREA_AUTHOR",author);
}
return author;
}
});
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String description = findOptionalString(A,null,"AREA_","description",piece,this.defined, false);
if(description != null)
{
A.setDescription(description);
defined.put("AREA_DESCRIPTION",description);
}
return description;
}
});
if(fillInArea(piece, defined, A, direction))
return A;
throw new CMException("Unable to build area for some reason.");
}
protected void updateLayoutDefinitions(final Map<String,Object> defined, final Map<String,Object> groupDefined,
final Map<List<LayoutNode>,Map<String,Object>> groupDefinitions, final List<List<LayoutNode>> roomGroups)
{
for (final String key : groupDefined.keySet())
{
if(key.startsWith("__"))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("AREADEF:"+key+"="+CMStrings.limit(groupDefined.get(key).toString(), 10));
defined.put(key, groupDefined.get(key));
for(final List<LayoutNode> group2 : roomGroups)
{
final Map<String,Object> groupDefined2 = groupDefinitions.get(group2);
if(groupDefined2!=groupDefined)
groupDefined2.put(key, groupDefined.get(key));
}
}
}
}
@SuppressWarnings("unchecked")
protected Room layOutRooms(final Area A, final LayoutManager layoutManager, final int size, final int direction, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","Using LayoutManager:"+layoutManager.name());
final Random random=new Random(System.currentTimeMillis());
final List<LayoutNode> roomsToLayOut = layoutManager.generate(size,direction);
if((roomsToLayOut==null)||(roomsToLayOut.size()==0))
throw new CMException("Unable to fill area of size "+size+" off layout "+layoutManager.name());
int numLeafs=0;
for(int i=0;i<roomsToLayOut.size();i++)
{
final LayoutNode node=roomsToLayOut.get(i);
if(node.type()==LayoutTypes.leaf)
numLeafs++;
if(node.links().size()==0)
throw new CMException("Created linkless node with "+layoutManager.name());
}
defined.put("AREA_NUMLEAFS", ""+numLeafs);
// now break our rooms into logical groups, generate those rooms.
final List<List<LayoutNode>> roomGroups = new Vector<List<LayoutNode>>();
final LayoutNode magicRoomNode = roomsToLayOut.get(0);
final HashSet<LayoutNode> nodesAlreadyGrouped=new HashSet<LayoutNode>();
boolean keepLooking=true;
while(keepLooking)
{
keepLooking=false;
for(int i=0;i<roomsToLayOut.size();i++)
{
final LayoutNode node=roomsToLayOut.get(i);
if(node.type()==LayoutTypes.leaf)
{
final Vector<LayoutNode> group=new Vector<LayoutNode>();
group.add(node);
nodesAlreadyGrouped.add(node);
for(final Integer linkDir : node.links().keySet())
{
final LayoutNode dirNode=node.links().get(linkDir);
if(!nodesAlreadyGrouped.contains(dirNode))
{
if((dirNode.type()==LayoutTypes.leaf)
||(dirNode.type()==LayoutTypes.interior)&&(node.isFlagged(LayoutFlags.offleaf)))
{
group.addElement(dirNode);
nodesAlreadyGrouped.add(dirNode);
}
}
}
for(final LayoutNode n : group)
roomsToLayOut.remove(n);
if(group.size()>0)
{
// randomize the leafs a bit
if(roomGroups.size()==0)
roomGroups.add(group);
else
roomGroups.add(random.nextInt(roomGroups.size()),group);
}
keepLooking=true;
break;
}
}
}
keepLooking=true;
while(keepLooking)
{
keepLooking=false;
for(int i=0;i<roomsToLayOut.size();i++)
{
final LayoutNode node=roomsToLayOut.get(i);
if(node.type()==LayoutTypes.street)
{
final List<LayoutNode> group=new Vector<LayoutNode>();
group.add(node);
nodesAlreadyGrouped.add(node);
final LayoutRuns run=node.getFlagRuns();
if(run==LayoutRuns.ns)
{
layoutFollow(node,LayoutTypes.street,Directions.NORTH,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.SOUTH,nodesAlreadyGrouped,group);
}
else
if(run==LayoutRuns.ew)
{
layoutFollow(node,LayoutTypes.street,Directions.EAST,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.WEST,nodesAlreadyGrouped,group);
}
else
if(run==LayoutRuns.nesw)
{
layoutFollow(node,LayoutTypes.street,Directions.NORTHEAST,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.SOUTHWEST,nodesAlreadyGrouped,group);
}
else
if(run==LayoutRuns.nwse)
{
layoutFollow(node,LayoutTypes.street,Directions.NORTHWEST,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.SOUTHEAST,nodesAlreadyGrouped,group);
}
else
{
int topDir=-1;
int topSize=-1;
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
if(node.links().get(Integer.valueOf(d))!=null)
{
final List<LayoutNode> grpCopy=new XArrayList<LayoutNode>(group);
final HashSet<LayoutNode> nodesAlreadyGroupedCopy=(HashSet<LayoutNode>)nodesAlreadyGrouped.clone();
layoutFollow(node,LayoutTypes.street,d,nodesAlreadyGroupedCopy,grpCopy);
if(node.links().get(Integer.valueOf(Directions.getOpDirectionCode(d)))!=null)
layoutFollow(node,LayoutTypes.street,Directions.getOpDirectionCode(d),nodesAlreadyGroupedCopy,grpCopy);
if(grpCopy.size()>topSize)
{
topSize=grpCopy.size();
topDir=d;
}
}
}
if(topDir>=0)
{
layoutFollow(node,LayoutTypes.street,topDir,nodesAlreadyGrouped,group);
if(node.links().get(Integer.valueOf(Directions.getOpDirectionCode(topDir)))!=null)
layoutFollow(node,LayoutTypes.street,Directions.getOpDirectionCode(topDir),nodesAlreadyGrouped,group);
}
}
for(final LayoutNode n : group)
roomsToLayOut.remove(n);
if(group.size()>0)
roomGroups.add(group);
keepLooking=true;
}
}
}
while(roomsToLayOut.size() >0)
{
final LayoutNode node=roomsToLayOut.get(0);
final Vector<LayoutNode> group=new Vector<LayoutNode>();
group.add(node);
nodesAlreadyGrouped.add(node);
layoutRecursiveFill(node,nodesAlreadyGrouped,group,node.type());
for(final LayoutNode n : group)
roomsToLayOut.remove(n);
roomGroups.add(group);
}
// make CERTAIN that the magic first room in the layout always
// gets ID#0.
List<LayoutNode> magicGroup=null;
for(int g=0;g<roomGroups.size();g++)
{
final List<LayoutNode> group=roomGroups.get(g);
if(group.contains(magicRoomNode))
{
magicGroup=group;
break;
}
}
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
for(int g=0;g<roomGroups.size();g++)
{
final Vector<LayoutNode> group=(Vector<LayoutNode>)roomGroups.get(g);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","GROUP:"+A.Name()+": "+group.firstElement().type().toString()+": "+group.size());
}
final Map<List<LayoutNode>,Map<String,Object>> groupDefinitions=new Hashtable<List<LayoutNode>,Map<String,Object>>();
for(final List<LayoutNode> group : roomGroups)
{
final Map<String,Object> newDefined=new Hashtable<String,Object>();
newDefined.putAll(defined);
groupDefinitions.put(group, newDefined);
}
Map<String,Object> groupDefined = groupDefinitions.get(magicGroup);
final Room magicRoom = processRoom(A,direction,piece,magicRoomNode,groupDefined);
for(final Map<String,Object> otherDefineds : groupDefinitions.values())
{
otherDefineds.remove("ROOMTAG_NODEGATEEXIT");
otherDefineds.remove("ROOMTAG_GATEEXITROOM");
}
updateLayoutDefinitions(defined,groupDefined,groupDefinitions,roomGroups);
//now generate the rooms and add them to the area
for(final List<LayoutNode> group : roomGroups)
{
groupDefined = groupDefinitions.get(group);
for(final LayoutNode node : group)
{
if(node!=magicRoomNode)
processRoom(A,direction,piece,node,groupDefined);
}
updateLayoutDefinitions(defined,groupDefined,groupDefinitions,roomGroups);
}
for(final Integer linkDir : magicRoomNode.links().keySet())
{
if(linkDir.intValue() == Directions.getOpDirectionCode(direction))
Log.errOut("MUDPercolator","Generated an override exit for "+magicRoom.roomID()+", direction="+direction+", layout="+layoutManager.name());
else
{
final LayoutNode linkNode=magicRoomNode.getLink(linkDir.intValue());
if((magicRoom.getRawExit(linkDir.intValue())==null) || (linkNode.room() == null))
Log.errOut("MUDPercolator","Generated an unpaired node for "+magicRoom.roomID());
else
magicRoom.rawDoors()[linkDir.intValue()]=linkNode.room();
}
}
//now do a final-link on the rooms
for(final List<LayoutNode> group : roomGroups)
{
for(final LayoutNode node : group)
{
final Room R=node.room();
if(node != magicRoomNode)
{
if((R==null)||(node.links().keySet().size()==0))
Log.errOut("MUDPercolator",layoutManager.name()+" generated a linkless node: "+node.toString());
else
for(final Integer linkDir : node.links().keySet())
{
final LayoutNode linkNode=node.getLink(linkDir.intValue());
if((R.getRawExit(linkDir.intValue())==null) || (linkNode.room() == null))
Log.errOut("MUDPercolator","Generated an unpaired node for "+R.roomID());
else
R.rawDoors()[linkDir.intValue()]=linkNode.room();
}
}
}
}
return magicRoom;
}
// vars created: LINK_DIRECTION, AREA_CLASS, AREA_NAME, AREA_DESCRIPTION, AREA_LAYOUT, AREA_SIZE
@Override
public boolean fillInArea(final XMLTag piece, final Map<String,Object> defined, final Area A, final int direction) throws CMException
{
final String layoutType = findStringNow("layout",piece,defined);
if((layoutType==null)||(layoutType.trim().length()==0))
throw new CMException("Unable to build area without defined layout");
final LayoutManager layoutManager = getLayoutManager(layoutType);
if(layoutManager == null)
throw new CMException("Undefined Layout "+layoutType);
defined.put("AREA_LAYOUT",layoutManager.name());
String size = findStringNow("size",piece,defined);
if(CMath.isMathExpression(size))
size=Integer.toString(CMath.parseIntExpression(size));
if((!CMath.isInteger(size))||(CMath.s_int(size)<=0))
throw new CMException("Unable to build area of size "+size);
defined.put("AREA_SIZE",size);
final List<String> ignoreStats=new XArrayList<String>(new String[]{"CLASS","NAME","DESCRIPTION","LAYOUT","SIZE"});
fillOutStatCodes(A, ignoreStats,"AREA_",piece,defined);
final List<Ability> aV = findAffects(A,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability AB=aV.get(i);
A.setSavable(true);
A.addNonUninvokableEffect(AB);
}
final List<Behavior> bV = findBehaviors(A,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
A.addBehavior(B);
}
CMLib.map().addArea(A); // necessary for proper naming.
try
{
layOutRooms(A, layoutManager, CMath.s_int(size), direction, piece, defined);
CMLib.map().delArea(A); // we added it for id assignment, now we are done.
}
catch(final Exception t)
{
CMLib.map().delArea(A);
CMLib.map().emptyAreaAndDestroyRooms(A);
A.destroy();
if(t instanceof CMException)
throw (CMException)t;
throw new CMException(t.getMessage(),t);
}
return true;
}
protected Room processRoom(final Area A, final int direction, final XMLTag piece, final LayoutNode node, final Map<String,Object> groupDefined)
throws CMException
{
for(final LayoutTags key : node.tags().keySet())
groupDefined.put("ROOMTAG_"+key.toString().toUpperCase(),node.tags().get(key));
final Exit[] exits=new Exit[Directions.NUM_DIRECTIONS()];
for(final Integer linkDir : node.links().keySet())
{
final LayoutNode linkNode = node.links().get(linkDir);
if(linkNode.room() != null)
{
final int opDir=Directions.getOpDirectionCode(linkDir.intValue());
exits[linkDir.intValue()]=linkNode.room().getExitInDir(opDir);
groupDefined.put("ROOMTITLE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),linkNode.room().displayText(null));
}
groupDefined.put("NODETYPE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),linkNode.type().name());
//else groupDefined.put("ROOMTITLE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),"");
groupDefined.put("ROOMLINK_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),"true");
}
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator",A.Name()+": type: "+node.type().toString());
final StringBuffer defs=new StringBuffer("");
for (final String key : groupDefined.keySet())
{
defs.append(key+"="+CMStrings.limit(groupDefined.get(key).toString(),10)+",");
}
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","DEFS: "+defs.toString());
}
final Room R=findRoom(A,piece, groupDefined, exits, direction);
if(R==null)
throw new CMException("Failure to generate room from "+piece.value());
R.setRoomID(A.getNewRoomID(null,-1));
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","ROOMID: "+R.roomID());
R.setArea(A);
A.addProperRoom(R);
node.setRoom(R);
groupDefined.remove("ROOMTAG_NODEGATEEXIT");
groupDefined.remove("ROOMTAG_GATEEXITROOM");
for(final LayoutTags key : node.tags().keySet())
groupDefined.remove("ROOMTAG_"+key.toString().toUpperCase());
for(final Integer linkDir : node.links().keySet())
{
groupDefined.remove("NODETYPE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase());
groupDefined.remove("ROOMLINK_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase());
groupDefined.remove("ROOMTITLE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase());
}
return R;
}
@Override
public List<MOB> findMobs(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
return findMobs(null,piece, defined, null);
}
protected List<MOB> findMobs(final Modifiable E,final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<MOB> V = new Vector<MOB>();
final String tagName="MOB";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Mob: "+CMStrings.limit(valPiece.value(),80)+"...");
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final MOB M=buildMob(valPiece,defined);
if(callBack != null)
callBack.willBuild(M, valPiece);
V.add(M);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Room findRoom(final Area A, final XMLTag piece, final Map<String,Object> defined, final Exit[] exits, final int directions) throws CMException
{
try
{
final String tagName="ROOM";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
{
return null;
}
while(choices.size()>0)
{
final XMLLibrary.XMLTag valPiece = choices.get(CMLib.dice().roll(1,choices.size(),-1));
choices.remove(valPiece);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(null,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final Map<String,Object> rDefined=new Hashtable<String,Object>();
rDefined.putAll(defined);
defineReward(null,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,rDefined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Room: "+CMStrings.limit(valPiece.value(),80)+"...");
Room R;
final String layoutType=valPiece.parms().get("LAYOUT");
if((layoutType!=null)&&(layoutType.length()>0))
{
final LayoutManager layoutManager = getLayoutManager(layoutType);
if(layoutManager == null)
throw new CMException("Undefined room Layout "+layoutType);
rDefined.put("ROOM_LAYOUT",layoutManager.name());
final String size = findStringNow("size",valPiece,rDefined);
if((!CMath.isInteger(size))||(CMath.s_int(size)<=0))
throw new CMException("Unable to build room layout of size "+size);
defined.put("ROOM_SIZE",size);
R=layOutRooms(A, layoutManager, CMath.s_int(size), directions, valPiece, rDefined);
}
else
{
final Exit[] rExits=exits.clone();
R=buildRoom(valPiece,rDefined,rExits,directions);
for(int e=0;e<rExits.length;e++)
exits[e]=rExits[e];
}
for (final String key : rDefined.keySet())
{
if(key.startsWith("_"))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("RGDEF:"+key+"="+CMStrings.limit(rDefined.get(key).toString(), 10));
defined.put(key,rDefined.get(key));
}
}
return R;
}
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
return null;
}
protected PairVector<Room,Exit[]> findRooms(final XMLTag piece, final Map<String,Object> defined, final Exit[] exits, final int direction) throws CMException
{
try
{
final PairVector<Room,Exit[]> DV = new PairVector<Room,Exit[]>();
final String tagName="ROOM";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return DV;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(null,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(null,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Exit[] theseExits=exits.clone();
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Room: "+CMStrings.limit(valPiece.value(),80)+"...");
final Room R=buildRoom(valPiece,defined,theseExits,direction);
DV.addElement(R,theseExits);
}
return DV;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Exit findExit(final Modifiable M, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final String tagName="EXIT";
final List<XMLLibrary.XMLTag> choices = getAllChoices(M,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return null;
final List<Exit> exitChoices = new Vector<Exit>();
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(M,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(M,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Exit: "+CMStrings.limit(valPiece.value(),80)+"...");
final Exit E=buildExit(valPiece,defined);
if(E!=null)
exitChoices.add(E);
}
if(exitChoices.size()==0)
return null;
return exitChoices.get(CMLib.dice().roll(1,exitChoices.size(),-1));
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
private static class Varidentifier
{
public int outerStart=-1;
public int outerEnd=-1;
public String var=null;
public boolean toLowerCase=false;
public boolean toUpperCase=false;
public boolean toCapitalized=false;
public boolean toPlural=false;
public boolean isMathExpression=false;
public boolean toOneWord=false;
}
protected List<Varidentifier> parseVariables(final String str)
{
int x=str.indexOf('$');
final List<Varidentifier> list=new XVector<Varidentifier>();
while((x>=0)&&(x<str.length()-1))
{
final Varidentifier var = new Varidentifier();
var.outerStart=x;
x++;
if((x<str.length())&&(str.charAt(x)=='{'))
{
int varstart=var.outerStart;
x++;
while((x<str.length()-2)&&(str.charAt(x+1)==':'))
{
switch(str.charAt(x))
{
case 'l': case 'L':
var.toLowerCase=true;
break;
case 'u': case 'U':
var.toUpperCase=true;
break;
case 'p': case 'P':
var.toPlural=true;
break;
case 'c': case 'C':
var.toCapitalized=true;
break;
case '_':
var.toOneWord=true;
break;
}
x+=2;
varstart+=2;
}
int depth=0;
while((x<str.length())
&&((str.charAt(x)!='}')||(depth>0)))
{
if(str.charAt(x)=='{')
depth++;
else
if(str.charAt(x)=='}')
depth--;
x++;
}
var.var = str.substring(varstart+2,x);
if(x<str.length())
x++;
var.outerEnd=x;
}
else
if((x<str.length())&&(str.charAt(x)=='['))
{
final int varstart=var.outerStart;
x++;
int depth=0;
while((x<str.length())
&&((str.charAt(x)!=']')||(depth>0)))
{
if(str.charAt(x)=='[')
depth++;
else
if(str.charAt(x)==']')
depth--;
x++;
}
var.var = str.substring(varstart+2,x);
var.isMathExpression=true;
if(x<str.length())
x++;
var.outerEnd=x;
}
else
{
while((x<str.length())&&((str.charAt(x)=='_')||Character.isLetterOrDigit(str.charAt(x))))
x++;
var.var = str.substring(var.outerStart+1,x);
var.outerEnd=x;
}
list.add(var);
x=str.indexOf('$',var.outerEnd);
}
return list;
}
protected String fillOutStatCode(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String stat, final XMLTag piece, final Map<String,Object> defined, final boolean debug)
{
if(!ignoreStats.contains(stat.toUpperCase().trim()))
{
try
{
return PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
String value;
if((E instanceof MOB) && (stat.equals("ABILITY")))
value = findOptionalString(E,ignoreStats,defPrefix,"HPMOD",piece,this.defined, debug);
else
value = findOptionalString(E,ignoreStats,defPrefix,stat,piece,this.defined, debug);
if(value != null)
{
E.setStat(stat, value);
if((defPrefix!=null)&&(defPrefix.length()>0))
addDefinition(defPrefix+stat,value,this.defined);
}
return value;
}
});
}
catch(final CMException e)
{
Log.errOut(e);
//should never happen
}
}
return null;
}
protected void fillOutStatCodes(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined)
{
final String[] statCodes = E.getStatCodes();
for (final String stat : statCodes)
{
fillOutStatCode(E,ignoreStats,defPrefix,stat,piece,defined, false);
}
}
protected void fillOutCopyStats(final Modifiable E, final Modifiable E2)
{
if((E2 instanceof MOB)&&(!((MOB)E2).isGeneric()))
{
for(final GenericBuilder.GenMOBCode stat : GenericBuilder.GenMOBCode.values())
{
if(stat != GenericBuilder.GenMOBCode.ABILITY) // because this screws up gen hit points
{
E.setStat(stat.name(), CMLib.coffeeMaker().getGenMobStat((MOB)E2,stat.name()));
}
}
}
else
if((E2 instanceof Item)&&(!((Item)E2).isGeneric()))
{
for(final GenericBuilder.GenItemCode stat : GenericBuilder.GenItemCode.values())
{
E.setStat(stat.name(),CMLib.coffeeMaker().getGenItemStat((Item)E2,stat.name()));
}
}
else
for(final String stat : E2.getStatCodes())
{
E.setStat(stat, E2.getStat(stat));
}
}
protected boolean fillOutCopyCodes(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String copyStatID = findOptionalStringNow(E,ignoreStats,defPrefix,"COPYOF",piece,defined, false);
if(copyStatID!=null)
{
final List<String> V=CMParms.parseCommas(copyStatID,true);
for(int v=0;v<V.size();v++)
{
String s = V.get(v);
if(s.startsWith("$"))
s=s.substring(1).trim();
final XMLTag statPiece =(XMLTag)defined.get(s.toUpperCase().trim());
if(statPiece == null)
{
Object o=CMClass.getMOBPrototype(s);
if(o==null)
o=CMClass.getItemPrototype(s);
if(o==null)
o=CMClass.getObjectOrPrototype(s);
if(!(o instanceof Modifiable))
throw new CMException("Invalid copystat: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final Modifiable E2=(Modifiable)o;
if(o instanceof MOB)
{
((MOB)E2).setBaseCharStats((CharStats)((MOB)o).baseCharStats().copyOf());
((MOB)E2).setBasePhyStats((PhyStats)((MOB)o).basePhyStats().copyOf());
((MOB)E2).setBaseState((CharState)((MOB)o).baseState().copyOf());
}
fillOutCopyStats(E,E2);
}
else
{
final XMLTag likePiece =(XMLTag)defined.get(s.toUpperCase().trim());
if(likePiece == null)
throw new CMException("Invalid copystat: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final BuildCallback callBack=new BuildCallback()
{
@Override
public void willBuild(final Environmental E2, final XMLTag XMLTag)
{
fillOutCopyStats(E,E2);
}
};
findItems(E,likePiece,defined,callBack);
findMobs(E,likePiece,defined,callBack);
findAbilities(E,likePiece,defined,callBack);
findExits(E,likePiece,defined,callBack);
}
}
return V.size()>0;
}
return false;
}
protected MOB buildMob(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
MOB M = null;
final List<String> ignoreStats=new XArrayList<String>();
boolean copyFilled = false;
if(classID.equalsIgnoreCase("catalog"))
{
final String name = findStringNow("NAME",piece,defined);
if((name == null)||(name.length()==0))
throw new CMException("Unable to build a catalog mob without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
M = CMLib.catalog().getCatalogMob(name);
if(M==null)
throw new CMException("Unable to find cataloged mob called '"+name+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
M=(MOB)M.copyOf();
CMLib.catalog().changeCatalogUsage(M,true);
addDefinition("MOB_CLASS",M.ID(),defined);
copyFilled=true;
}
else
{
M = CMClass.getMOB(classID);
if(M == null)
throw new CMException("Unable to build mob on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
addDefinition("MOB_CLASS",classID,defined);
if(M.isGeneric())
{
copyFilled = fillOutCopyCodes(M,ignoreStats,"MOB_",piece,defined);
String name = fillOutStatCode(M,ignoreStats,"MOB_","NAME",piece,defined, false);
if((!copyFilled) && ((name == null)||(name.length()==0)))
name = fillOutStatCode(M,ignoreStats,"MOB_","NAME",piece,defined, false);
if((!copyFilled) && ((name == null)||(name.length()==0)))
{
name = fillOutStatCode(M,ignoreStats,"MOB_","NAME",piece,defined, true);
if((!copyFilled) && ((name == null)||(name.length()==0)))
throw new CMException("Unable to build a mob without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
if((name != null)&&(name.length()>0))
M.setName(name);
}
}
final MOB mob=M;
addDefinition("MOB_NAME",M.Name(),defined);
if(!copyFilled)
M.baseCharStats().setMyRace(CMClass.getRace("StdRace"));
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(mob,ignoreStats,"MOB_","LEVEL",piece,this.defined, false);
if((value != null)&&(value.length()>0))
{
mob.setStat("LEVEL",value);
addDefinition("MOB_LEVEL",value,this.defined);
CMLib.leveler().fillOutMOB(mob,mob.basePhyStats().level());
CMLib.leveler().fillOutMOB(mob,mob.basePhyStats().level());
}
return value;
}
});
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(mob,ignoreStats,"MOB_","GENDER",piece,this.defined, false);
if((value != null)&&(value.length()>0))
{
mob.baseCharStats().setStat(CharStats.STAT_GENDER,value.charAt(0));
addDefinition("MOB_GENDER",value,this.defined);
}
else
mob.baseCharStats().setStat(CharStats.STAT_GENDER,CMLib.dice().rollPercentage()>50?'M':'F');
PostProcessAttempter(this.defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(mob,ignoreStats,"MOB_","RACE",piece,this.defined, false);
if((value != null)&&(value.length()>0))
{
mob.setStat("RACE",value);
addDefinition("MOB_RACE",value,this.defined);
Race R=CMClass.getRace(value);
if(R==null)
{
final List<Race> races=findRaces(mob,piece, this.defined);
if(races.size()>0)
R=races.get(CMLib.dice().roll(1, races.size(), -1));
}
if(R!=null)
R.setHeightWeight(mob.basePhyStats(),(char)mob.baseCharStats().getStat(CharStats.STAT_GENDER));
}
return value;
}
});
return value;
}
});
PostProcessAttempter(defined, new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final List<XMLLibrary.XMLTag> choices = getAllChoices(mob,ignoreStats,"MOB_","FACTION", piece, this.defined, true);
if((choices!=null)&&(choices.size()>0))
{
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
final String f = valPiece.getParmValue("ID");
final String v = valPiece.getParmValue("VALUE");
mob.addFaction(f, Integer.parseInt(v));
}
}
return "";
}
});
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","NAME","LEVEL","GENDER"}));
fillOutStatCodes(M,ignoreStats,"MOB_",piece,defined);
M.recoverCharStats();
M.recoverPhyStats();
M.recoverMaxState();
final List<Item> items = findItems(piece,defined);
for(int i=0;i<items.size();i++)
{
final Item I=items.get(i);
final boolean wearable = (I.phyStats().sensesMask()&PhyStats.SENSE_ITEMNOAUTOWEAR)==0;
M.addItem(I);
I.setSavable(true);
if(wearable)
I.wearIfPossible(M);
}
final List<Ability> aV = findAffects(M,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability A=aV.get(i);
A.setSavable(true);
M.addNonUninvokableEffect(A);
}
final List<Behavior> bV= findBehaviors(M,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
M.addBehavior(B);
}
final List<Ability> abV = findAbilities(M,piece,defined,null);
for(int i=0;i<abV.size();i++)
{
final Ability A=abV.get(i);
A.setSavable(true);
M.addAbility(A);
}
final ShopKeeper SK=CMLib.coffeeShops().getShopKeeper(M);
if(SK!=null)
{
final CoffeeShop shop=(SK instanceof Librarian)?((Librarian)SK).getBaseLibrary():SK.getShop();
final List<Triad<Environmental,Integer,Long>> iV = findShopInventory(M,piece,defined);
if(iV.size()>0)
shop.emptyAllShelves();
for(int i=0;i<iV.size();i++)
shop.addStoreInventory(iV.get(i).first,iV.get(i).second.intValue(),iV.get(i).third.intValue());
}
M.recoverCharStats();
M.recoverPhyStats();
M.recoverMaxState();
M.text();
M.setMiscText(M.text());
M.recoverCharStats();
M.recoverPhyStats();
M.recoverMaxState();
return M;
}
protected List<Exit> findExits(final Modifiable M,final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<Exit> V = new Vector<Exit>();
final String tagName="EXIT";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(M,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Exit: "+CMStrings.limit(valPiece.value(),80)+"...");
defineReward(M,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Exit E=buildExit(valPiece,defined);
if(callBack != null)
callBack.willBuild(E, valPiece);
V.add(E);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
// remember to check ROOMLINK_DIR for N,S,E,W,U,D,etc..
protected Exit buildExit(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final List<String> ignoreStats=new XArrayList<String>();
final String classID = findStringNow("class",piece,defined);
final Exit E = CMClass.getExit(classID);
if(E == null)
throw new CMException("Unable to build exit on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
addDefinition("EXIT_CLASS",classID,defined);
ignoreStats.add("CLASS");
fillOutCopyCodes(E,ignoreStats,"EXIT_",piece,defined);
fillOutStatCodes(E,ignoreStats,"EXIT_",piece,defined);
final List<Ability> aV = findAffects(E,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability A=aV.get(i);
A.setSavable(true);
E.addNonUninvokableEffect(A);
}
final List<Behavior> bV= findBehaviors(E,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
E.addBehavior(B);
}
E.text();
E.setMiscText(E.text());
E.recoverPhyStats();
return E;
}
protected List<Triad<Environmental,Integer,Long>> findShopInventory(final Modifiable E,final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Triad<Environmental,Integer,Long>> V = new Vector<Triad<Environmental,Integer,Long>>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,"SHOPINVENTORY", piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag shopPiece = choices.get(c);
if(shopPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(shopPiece.getParmValue("VALIDATE")),shopPiece, defined))
continue;
final String baseNumber[] = { "1" };
final String basePrice[] = { "-1" };
try
{
final String baseStr=shopPiece.getParmValue("NUMBER");
if(baseStr != null)
baseNumber[0]=baseStr;
}
catch (final Exception e)
{
}
try
{
final String baseStr=shopPiece.getParmValue("PRICE");
if(baseStr != null)
basePrice[0]=baseStr;
}
catch (final Exception e)
{
}
final BuildCallback callBack=new BuildCallback()
{
@Override
public void willBuild(final Environmental E, final XMLTag XMLTag)
{
String numbStr=XMLTag.getParmValue("NUMBER");
if(numbStr == null)
numbStr=baseNumber[0];
int number;
try
{
number = CMath.parseIntExpression(strFilter(E, null, null, numbStr.trim(), piece, defined));
}
catch (final Exception e)
{
number = 1;
}
numbStr=XMLTag.getParmValue("PRICE");
if(numbStr == null)
numbStr=basePrice[0];
long price;
try
{
price = CMath.parseLongExpression(strFilter(E, null, null, numbStr.trim(), piece, defined));
}
catch (final Exception e)
{
price = -1;
}
V.add(new Triad<Environmental,Integer,Long>(E,Integer.valueOf(number),Long.valueOf(price)));
}
};
findItems(E,shopPiece,defined,callBack);
findMobs(E,shopPiece,defined,callBack);
findAbilities(E,shopPiece,defined,callBack);
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Set<String> getPrevouslyDefined(final Map<String,Object> defined, final String prefix)
{
final Set<String> prevSet=new HashSet<String>();
for(final String key : defined.keySet())
{
if(key.toUpperCase().startsWith(prefix.toUpperCase()))
prevSet.add(key.toUpperCase());
}
return prevSet;
}
protected void clearNewlyDefined(final Map<String,Object> defined, final Set<String> exceptSet, final String prefix)
{
final Set<String> clearSet=new HashSet<String>();
for(final String key : defined.keySet())
if(key.toUpperCase().startsWith(prefix.toUpperCase())
&& (!exceptSet.contains(key.toUpperCase()))
&& (!key.startsWith("_")))
clearSet.add(key);
for(final String key : clearSet)
defined.remove(key);
}
@Override
public List<Item> findItems(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
return findItems(null,piece, defined, null);
}
protected List<Item> findItems(final Modifiable E,final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<Item> V = new Vector<Item>();
final String tagName="ITEM";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Item: "+CMStrings.limit(valPiece.value(),80)+"...");
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
try
{
for(final Item I : buildItem(valPiece,defined))
{
if(callBack != null)
callBack.willBuild(I, valPiece);
V.add(I);
}
}
catch(final CMException e)
{
throw e;
}
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Item> findContents(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Item> V = new Vector<Item>();
final String tagName="CONTENT";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Found Content: "+valPiece.value());
V.addAll(findItems(valPiece,defined));
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected String getMetacraftFilter(String recipe, final XMLTag piece, final Map<String,Object> defined, final Triad<Integer,Integer,Class<?>[]> filter) throws CMException
{
int levelLimit=-1;
int levelFloor=-1;
Class<?>[] deriveClasses=new Class[0];
final Map.Entry<Character, String>[] otherParms=CMStrings.splitMulti(recipe, splitters);
recipe=otherParms[0].getValue();
if(otherParms.length==1)
return recipe;
for(int i=1;i<otherParms.length;i++)
{
if(otherParms[i].getKey().charValue()=='<')
{
final String lvlStr=strFilterNow(null,null,null,otherParms[i].getValue().trim(),piece, defined);
if(CMath.isMathExpression(lvlStr))
{
levelLimit=CMath.parseIntExpression(lvlStr);
if((levelLimit==0)||(levelLimit<levelFloor))
levelLimit=-1;
}
}
else
if(otherParms[i].getKey().charValue()=='>')
{
final String lvlStr=strFilterNow(null,null,null,otherParms[i].getValue().trim(),piece, defined);
if(CMath.isMathExpression(lvlStr))
{
levelFloor=CMath.parseIntExpression(lvlStr);
if((levelFloor==0)||((levelFloor>levelLimit)&&(levelLimit>0)))
levelFloor=-1;
}
}
else
if(otherParms[i].getKey().charValue()=='=')
{
final String classStr=strFilterNow(null,null,null,otherParms[i].getValue().trim(),piece, defined);
final Object O=CMClass.getItemPrototype(classStr);
if(O!=null)
{
deriveClasses=Arrays.copyOf(deriveClasses, deriveClasses.length+1);
deriveClasses[deriveClasses.length-1]=O.getClass();
}
else
throw new CMException("Unknown metacraft class= "+classStr);
}
}
if(levelLimit>0)
filter.first=Integer.valueOf(levelLimit);
if(levelFloor>0)
filter.second=Integer.valueOf(levelFloor);
if(deriveClasses.length>0)
filter.third=deriveClasses;
return recipe;
}
@SuppressWarnings("unchecked")
protected List<ItemCraftor.ItemKeyPair> craftAllOfThisRecipe(final ItemCraftor skill, final int material, final Map<String,Object> defined)
{
List<ItemCraftor.ItemKeyPair> skillContents=(List<ItemCraftor.ItemKeyPair>)defined.get("____COFFEEMUD_"+skill.ID()+"_"+material+"_true");
if(skillContents==null)
{
if(material>=0)
skillContents=skill.craftAllItemSets(material, true);
else
skillContents=skill.craftAllItemSets(true);
if(skillContents==null)
return null;
defined.put("____COFFEEMUD_"+skill.ID()+"_"+material+"_true",skillContents);
}
final List<ItemCraftor.ItemKeyPair> skillContentsCopy=new Vector<ItemCraftor.ItemKeyPair>(skillContents.size());
skillContentsCopy.addAll(skillContents);
return skillContentsCopy;
}
protected boolean checkMetacraftItem(final Item I, final Triad<Integer,Integer,Class<?>[]> filter)
{
final int levelLimit=filter.first.intValue();
final int levelFloor=filter.second.intValue();
final Class<?>[] deriveClasses=filter.third;
if(((levelLimit>0) && (I.basePhyStats().level() > levelLimit))
||((levelFloor>0) && (I.basePhyStats().level() < levelFloor)))
return false;
if(deriveClasses.length==0)
return true;
for(final Class<?> C : deriveClasses)
{
if(C.isAssignableFrom(I.getClass()))
return true;
}
return false;
}
protected List<Item> buildItem(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final Map<String,Object> preContentDefined = new SHashtable<String,Object>(defined);
final String classID = findStringNow("class",piece,defined);
final List<Item> contents = new Vector<Item>();
final List<String> ignoreStats=new XArrayList<String>();
final int senseFlag = CMath.s_bool(findOptionalStringNow(null,null,null,"nowear",piece,defined,false)) ? PhyStats.SENSE_ITEMNOAUTOWEAR : 0;
if(classID.toLowerCase().startsWith("metacraft"))
{
final String classRest=classID.substring(9).toLowerCase().trim();
final Triad<Integer,Integer,Class<?>[]> filter = new Triad<Integer,Integer,Class<?>[]>(Integer.valueOf(-1),Integer.valueOf(-1),new Class<?>[0]);
String recipe="anything";
if(classRest.startsWith(":"))
{
recipe=getMetacraftFilter(classRest.substring(1).trim(), piece, defined, filter);
}
else
{
recipe = findStringNow("NAME",piece,defined);
if((recipe == null)||(recipe.length()==0))
throw new CMException("Unable to metacraft with malformed class Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
final String materialStr = findOptionalStringNow(null,null,null,"material",piece,defined, false);
int material=-1;
if(materialStr!=null)
material = RawMaterial.CODES.FIND_IgnoreCase(materialStr);
final List<ItemCraftor> craftors=new Vector<ItemCraftor>();
for(final Enumeration<Ability> e=CMClass.abilities();e.hasMoreElements();)
{
final Ability A=e.nextElement();
if(A instanceof ItemCraftor)
craftors.add((ItemCraftor)A);
}
if(recipe.equalsIgnoreCase("anything"))
{
final long startTime=System.currentTimeMillis();
while((contents.size()==0)&&((System.currentTimeMillis()-startTime)<1000))
{
final ItemCraftor skill=craftors.get(CMLib.dice().roll(1,craftors.size(),-1));
if(skill.fetchRecipes().size()>0)
{
final List<ItemCraftor.ItemKeyPair> skillContents=craftAllOfThisRecipe(skill,material,defined);
if(skillContents.size()==0) // preliminary error messaging, just for the craft skills themselves
Log.errOut("MUDPercolator","Tried metacrafting anything, got "+Integer.toString(skillContents.size())+" from "+skill.ID());
else
for(int i=skillContents.size()-1;i>=0;i--)
{
final Item I=skillContents.get(i).item;
if(!checkMetacraftItem(I, filter))
skillContents.remove(i);
}
if(skillContents.size()>0)
{
final Item I=(Item)skillContents.get(CMLib.dice().roll(1,skillContents.size(),-1)).item.copyOf();
contents.add(I);
}
}
}
}
else
if(recipe.toLowerCase().startsWith("any-"))
{
List<ItemCraftor.ItemKeyPair> skillContents=null;
recipe=recipe.substring(4).trim();
for(final ItemCraftor skill : craftors)
{
if(skill.ID().equalsIgnoreCase(recipe))
{
skillContents=craftAllOfThisRecipe(skill,material,defined);
if((skillContents==null)||(skillContents.size()==0)) // this is just for checking the skills themselves
Log.errOut("MUDPercolator","Tried metacrafting any-"+recipe+", got "+Integer.toString(contents.size())+" from "+skill.ID());
else
for(int i=skillContents.size()-1;i>=0;i--)
{
final Item I=skillContents.get(i).item;
if(!checkMetacraftItem(I, filter))
skillContents.remove(i);
}
break;
}
}
if((skillContents!=null)&&(skillContents.size()>0))
{
final Item I=(Item)skillContents.get(CMLib.dice().roll(1,skillContents.size(),-1)).item.copyOf();
contents.add(I);
}
}
else
if(recipe.toLowerCase().startsWith("all"))
{
List<ItemCraftor.ItemKeyPair> skillContents=null;
recipe=recipe.substring(3).startsWith("-")?recipe.substring(4).trim():"";
for(final ItemCraftor skill : craftors)
{
if(skill.ID().equalsIgnoreCase(recipe)||(recipe.length()==0))
{
skillContents=craftAllOfThisRecipe(skill,material,defined);
if((skillContents==null)||(skillContents.size()==0)) // this is just for checking the skills themselves
Log.errOut("MUDPercolator","Tried metacrafting any-"+recipe+", got "+Integer.toString(contents.size())+" from "+skill.ID());
else
for(int i=skillContents.size()-1;i>=0;i--)
{
final Item I=skillContents.get(i).item;
if(!checkMetacraftItem(I, filter))
skillContents.remove(i);
}
while((skillContents!=null)&&(skillContents.size()>0))
{
final Item I=(Item)skillContents.remove(0).item.copyOf();
contents.add(I);
}
if(recipe.length()>0)
break;
}
}
}
else
{
for(final ItemCraftor skill : craftors)
{
final List<List<String>> V=skill.matchingRecipeNames(recipe,false);
if((V!=null)&&(V.size()>0))
{
ItemCraftor.ItemKeyPair pair;
if(material>=0)
pair=skill.craftItem(recipe,material,true, false);
else
pair=skill.craftItem(recipe,-1,true, false);
if(pair!=null)
{
contents.add(pair.item);
break;
}
}
}
for(int i=contents.size()-1;i>=0;i--)
{
final Item I=contents.get(i);
if(!checkMetacraftItem(I, filter))
contents.remove(i);
}
if(contents.size()==0)
{
for(final ItemCraftor skill : craftors)
{
final List<List<String>> V=skill.matchingRecipeNames(recipe,true);
if((V!=null)&&(V.size()>0))
{
ItemCraftor.ItemKeyPair pair;
if(material>=0)
pair=skill.craftItem(recipe,material,true, false);
else
pair=skill.craftItem(recipe,0,true, false);
if(pair!=null)
{
contents.add(pair.item);
break;
}
}
}
}
for(int i=contents.size()-1;i>=0;i--)
{
final Item I=contents.get(i);
if(!checkMetacraftItem(I, filter))
contents.remove(i);
}
}
if(contents.size()==0)
{
if(filter.equals(emptyMetacraftFilter))
throw new CMException("Unable to metacraft an item called '"+recipe+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
else
return new ArrayList<Item>(0);
}
for(final Item I : contents)
{
addDefinition("ITEM_CLASS",I.ID(),defined);
addDefinition("ITEM_NAME",I.Name(),defined); // define so we can mess with it
addDefinition("ITEM_LEVEL",""+I.basePhyStats().level(),defined); // define so we can mess with it
fillOutStatCode(I,ignoreStats,"ITEM_","NAME",piece,defined, false);
fillOutStatCode(I,ignoreStats,"ITEM_","LEVEL",piece,defined, false);
}
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","MATERIAL","NAME","LEVEL"}));
}
else
if(classID.equalsIgnoreCase("catalog"))
{
final String name = findStringNow("NAME",piece,defined);
if((name == null)||(name.length()==0))
throw new CMException("Unable to build a catalog item without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
Item I = CMLib.catalog().getCatalogItem(name);
if(I==null)
throw new CMException("Unable to find cataloged item called '"+name+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
I=(Item)I.copyOf();
CMLib.catalog().changeCatalogUsage(I,true);
contents.add(I);
addDefinition("ITEM_CLASS",I.ID(),defined);
addDefinition("ITEM_NAME",I.Name(),defined); // define so we can mess with it
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","NAME"}));
}
else
{
final Item I = CMClass.getItem(classID);
if(I == null)
throw new CMException("Unable to build item on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
contents.add(I);
addDefinition("ITEM_CLASS",classID,defined);
if(I.isGeneric())
{
final boolean filledOut = fillOutCopyCodes(I,ignoreStats,"ITEM_",piece,defined);
final String name = fillOutStatCode(I,ignoreStats,"ITEM_","NAME",piece,defined, false);
if((!filledOut) && ((name == null)||(name.length()==0)))
throw new CMException("Unable to build an item without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
if((name != null)&&(name.length()>0))
I.setName(name);
}
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","NAME"}));
addDefinition("ITEM_NAME",I.Name(),defined); // define so we can mess with it
}
final int contentSize=contents.size();
for(int it=0;it<contentSize;it++) // no iterator, please!!
{
final Item I=contents.get(it);
fillOutStatCodes(I,ignoreStats,"ITEM_",piece,defined);
I.recoverPhyStats();
CMLib.itemBuilder().balanceItemByLevel(I);
I.recoverPhyStats();
fillOutStatCodes(I,ignoreStats,"ITEM_",piece,defined);
I.recoverPhyStats();
if(I instanceof Container)
{
final List<Item> V= findContents(piece,new SHashtable<String,Object>(preContentDefined));
for(int i=0;i<V.size();i++)
{
final Item I2=V.get(i);
I2.setContainer((Container)I);
contents.add(I2);
}
}
{
final List<Ability> V= findAffects(I,piece,defined,null);
for(int i=0;i<V.size();i++)
{
final Ability A=V.get(i);
A.setSavable(true);
I.addNonUninvokableEffect(A);
}
}
final List<Behavior> V = findBehaviors(I,piece,defined);
for(int i=0;i<V.size();i++)
{
final Behavior B=V.get(i);
B.setSavable(true);
I.addBehavior(B);
}
I.recoverPhyStats();
I.text();
I.setMiscText(I.text());
I.recoverPhyStats();
I.phyStats().setSensesMask(I.phyStats().sensesMask()|senseFlag);
}
return contents;
}
protected List<Ability> findAffects(final Modifiable E, final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
return findAbilities(E,"AFFECT",piece,defined,callBack);
}
protected List<Ability> findAbilities(final Modifiable E, final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
return findAbilities(E,"ABILITY",piece,defined,callBack);
}
protected List<Ability> findAbilities(final Modifiable E, final String tagName, final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<Ability> V = new Vector<Ability>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE")
&& !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Ability A=buildAbility(E,valPiece,defined);
if(callBack != null)
callBack.willBuild(A, valPiece);
V.add(A);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Behavior> findBehaviors(final Modifiable E,final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Behavior> V = new Vector<Behavior>();
final String tagName="BEHAVIOR";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Behavior B=buildBehavior(E,valPiece,defined);
V.add(B);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Race> findRaces(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException, PostProcessException
{
final List<Race> V = new Vector<Race>();
final String tagName="RACE";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Race R=buildGenRace(E,valPiece,defined);
V.add(R);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
protected Ability buildAbility(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
Ability A=CMClass.getAbility(classID);
if(A == null)
A=CMClass.findAbility(classID);
if(A == null)
throw new CMException("Unable to build ability on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final Ability aA=A;
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(E,null,null,"PARMS",piece,this.defined, false);
if(value != null)
aA.setMiscText(value);
return value;
}
});
return A;
}
protected Behavior buildBehavior(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
Behavior B=CMClass.getBehavior(classID);
if(B == null)
B=CMClass.findBehavior(classID);
if(B == null)
throw new CMException("Unable to build behavior on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final Behavior bB=B;
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(E,null,null,"PARMS",piece,this.defined, false);
if(value != null)
bB.setParms(value);
return value;
}
});
return B;
}
protected List<AbilityMapping> findRaceAbles(final Modifiable E, final String tagName, final String prefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<AbilityMapping> V = new Vector<AbilityMapping>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,prefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,prefix,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,prefix,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final String classID = findStringNow("CLASS",valPiece,defined);
Ability A=CMClass.getAbility(classID);
if(A == null)
A=CMClass.findAbility(classID);
if(A == null)
throw new CMException("Unable to build ability on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
defined.put(prefix+"CLASS", classID);
final AbilityMapping mapA=CMLib.ableMapper().newAbilityMapping().ID(classID);
String value;
value=findOptionalStringNow(E, null, prefix, "PARMS", valPiece, defined, false);
if(value != null)
{
mapA.defaultParm(value);
defined.put(prefix+"PARMS", value);
}
value=findOptionalStringNow(E, null, prefix, "PROFF", valPiece, defined, false);
if(value != null)
{
mapA.defaultProficiency(CMath.parseIntExpression(value));
defined.put(prefix+"PROFF", Integer.valueOf(mapA.defaultProficiency()));
}
value=findOptionalStringNow(E, null, prefix, "LEVEL", valPiece, defined, false);
if(value != null)
{
mapA.qualLevel(CMath.parseIntExpression(value));
defined.put(prefix+"LEVEL", Integer.valueOf(mapA.qualLevel()));
}
value=findOptionalStringNow(E, null, prefix, "QUALIFY", valPiece, defined, false);
if(value != null)
{
mapA.autoGain(!CMath.s_bool(value));
defined.put(prefix+"QUALIFY", value);
}
V.add(mapA);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Item> getRaceItems(final Modifiable E, final String tagName, final String prefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Item> V = new Vector<Item>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,prefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Found Race Item: "+valPiece.value());
V.addAll(findItems(valPiece,defined));
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Race buildGenRace(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
Race R=CMClass.getRace(classID);
if( R != null)
return R;
R=(Race)CMClass.getRace("GenRace").copyOf();
int numStatsFound=0;
for(final String stat : R.getStatCodes())
{
try
{
if(findOptionalString(null, null, null, stat, piece, defined, false)!=null)
numStatsFound++;
}
catch(final PostProcessException pe)
{
numStatsFound++;
}
}
if(numStatsFound<5)
throw new CMException("Too few fields to build race on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
R.setRacialParms("<RACE><ID>"+CMStrings.capitalizeAndLower(classID)+"</ID><NAME>"+CMStrings.capitalizeAndLower(classID)+"</NAME></RACE>");
CMClass.addRace(R);
addDefinition("RACE_CLASS",R.ID(),defined); // define so we can mess with it
R.setStat("NAME", findStringNow("name",piece,defined));
addDefinition("RACE_NAME",R.name(),defined); // define so we can mess with it
final List<String> ignoreStats=new XArrayList<String>(new String[]{"CLASS","NAME"});
final List<Item> raceWeapons=getRaceItems(E,"WEAPON","RACE_WEAPON_",piece,defined);
if(raceWeapons.size()>0)
{
final Item I=raceWeapons.get(CMLib.dice().roll(1, raceWeapons.size(), -1));
R.setStat("WEAPONCLASS", I.ID());
R.setStat("WEAPONXML", I.text());
}
ignoreStats.addAll(Arrays.asList(new String[]{"WEAPONCLASS","WEAPONXML"}));
final List<Item> raceResources=getRaceItems(E,"RESOURCES","RACE_RESOURCE_",piece,defined);
R.setStat("NUMRSC", ""+raceResources.size());
for(int i=0;i<raceResources.size();i++)
{
final Item I=raceResources.get(i);
R.setStat("GETRSCID"+i, I.ID());
R.setStat("GETRSCPARM"+i, ""+I.text());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMRSC","GETRSCID","GETRSCPARM"}));
final List<Item> raceOutfit=getRaceItems(E,"OUTFIT","RACE_RESOURCE_",piece,defined);
R.setStat("NUMOFT", ""+raceOutfit.size());
for(int i=0;i<raceOutfit.size();i++)
{
final Item I=raceOutfit.get(i);
R.setStat("GETOFTID"+i, I.ID());
R.setStat("GETOFTPARM"+i, ""+I.text());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMOFT","GETOFTID","GETOFTPARM"}));
final List<AbilityMapping> rables = findRaceAbles(E,"ABILITY","RACE_ABLE_",piece,defined);
R.setStat("NUMRABLE", ""+rables.size());
for(int i=0;i<rables.size();i++)
{
final AbilityMapping ableMap=rables.get(i);
R.setStat("GETRABLE"+i, ableMap.abilityID());
R.setStat("GETRABLEPROF"+i, ""+ableMap.defaultProficiency());
R.setStat("GETRABLEQUAL"+i, ""+(!ableMap.autoGain()));
R.setStat("GETRABLELVL"+i, ""+ableMap.qualLevel());
R.setStat("GETRABLEPARM"+i, ableMap.defaultParm());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMRABLE","GETRABLE","GETRABLEPROF","GETRABLEQUAL","GETRABLELVL","GETRABLEPARM"}));
final List<AbilityMapping> cables = findRaceAbles(E,"CULTUREABILITY","RACE_CULT_ABLE_",piece,defined);
R.setStat("NUMCABLE", ""+cables.size());
for(int i=0;i<cables.size();i++)
{
final AbilityMapping ableMap=cables.get(i);
R.setStat("GETCABLE"+i, ableMap.abilityID());
R.setStat("GETCABLEPROF"+i, ""+ableMap.defaultProficiency());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMCABLE","GETCABLE","GETCABLEPROF"}));
final List<AbilityMapping> reffs = findRaceAbles(E,"AFFECT","RACE_EFFECT_",piece,defined);
R.setStat("NUMREFF", ""+reffs.size());
for(int i=0;i<reffs.size();i++)
{
final AbilityMapping ableMap=reffs.get(i);
R.setStat("GETREFF"+i, ableMap.abilityID());
R.setStat("GETREFFPARM"+i, ""+ableMap.defaultParm());
R.setStat("GETREFFLVL"+i, ""+ableMap.qualLevel());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMREFF","GETREFF","GETREFFPARM","GETREFFLVL"}));
final List<AbilityMapping> iables = findRaceAbles(E,"IMMUNITY","RACE_IMMUNITY_",piece,defined);
R.setStat("NUMIABLE", ""+reffs.size());
for(int i=0;i<iables.size();i++)
{
final AbilityMapping ableMap=reffs.get(i);
R.setStat("GETIABLE"+i, ableMap.abilityID());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMIABLE","GETIABLE"}));
fillOutStatCodes(R,ignoreStats,"RACE_",piece,defined);
CMLib.database().DBCreateRace(R.ID(),R.racialParms());
return R;
}
protected void addDefinition(String definition, final String value, final Map<String,Object> defined)
{
definition=definition.toUpperCase().trim();
defined.put(definition, value);
if(definition.toUpperCase().endsWith("S"))
definition+="ES";
else
definition+="S";
final String def = (String)defined.get(definition);
if(def==null)
defined.put(definition, value);
else defined.put(definition, def+","+value);
}
protected String findOptionalStringNow(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined, final boolean debug)
{
try
{
return findOptionalString(E,ignoreStats,defPrefix,tagName, piece, defined, false);
}
catch(final PostProcessException x)
{
if(debug)
Log.errOut(x);
return null;
}
}
protected String findOptionalString(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined, final boolean debug) throws PostProcessException
{
try
{
return findString(E,ignoreStats,defPrefix,tagName, piece, defined);
}
catch(final CMException x)
{
if(debug)
Log.errOut(x);
return null;
}
}
@Override
public void defineReward(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
defineReward(null, null, null,piece,piece.value(),defined);
}
protected void defineReward(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final String value, final Map<String,Object> defined) throws CMException
{
try
{
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("DEFINE"),piece,value,defined,true);
}
catch(final PostProcessException pe)
{
throw new CMException("Post-processing not permitted: "+pe.getMessage(),pe);
}
}
@Override
public void preDefineReward(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
preDefineReward(null,null,null,piece,defined);
}
protected void preDefineReward(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("PREDEFINE"),piece,piece.value(),defined,false);
}
catch(final PostProcessException pe)
{
throw new CMException("Post-processing not permitted: "+pe.getMessage(),pe);
}
}
protected void defineReward(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String defineString, final XMLTag piece, final Object value, final Map<String,Object> defined, final boolean recurseAllowed) throws CMException, PostProcessException
{
if((defineString!=null)&&(defineString.trim().length()>0))
{
final List<String> V=CMParms.parseCommas(defineString,true);
for (String defVar : V)
{
Object definition=value;
final int x=defVar.indexOf('=');
if(x==0)
continue;
if(x>0)
{
definition=defVar.substring(x+1).trim();
defVar=defVar.substring(0,x).toUpperCase().trim();
switch(defVar.charAt(defVar.length()-1))
{
case '+':
case '-':
case '*':
case '/':
{
final char plusMinus=defVar.charAt(defVar.length()-1);
defVar=defVar.substring(0,defVar.length()-1).trim();
String oldVal=(String)defined.get(defVar.toUpperCase().trim());
if((oldVal==null)||(oldVal.trim().length()==0))
oldVal="0";
definition=oldVal+plusMinus+definition;
break;
}
}
}
if(definition==null)
definition="!";
if(definition instanceof String)
{
definition=strFilter(E,ignoreStats,defPrefix,(String)definition,piece, defined);
if(CMath.isMathExpression((String)definition))
definition=Integer.toString(CMath.s_parseIntExpression((String)definition));
}
if(defVar.trim().length()>0)
defined.put(defVar.toUpperCase().trim(), definition);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","DEFINE:"+defVar.toUpperCase().trim()+"="+definition);
}
}
final XMLTag parentPiece = piece.parent();
if((parentPiece!=null)&&(parentPiece.tag().equalsIgnoreCase(piece.tag()))&&(recurseAllowed))
defineReward(E,ignoreStats,defPrefix,parentPiece.getParmValue("DEFINE"),parentPiece,value,defined,recurseAllowed);
}
protected String findStringNow(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
return findString(E,ignoreStats,defPrefix,tagName,piece,defined);
}
catch(final PostProcessException pe)
{
throw new CMException("Post processing not permitted",pe);
}
}
protected String replaceLineStartsWithIgnoreCase(final String wholeText, final String lineStarter, final String fullNewLine)
{
final int x=wholeText.toLowerCase().indexOf(lineStarter.toLowerCase());
if(x>0)
{
int y=wholeText.indexOf('\n',x+1);
final int z=wholeText.indexOf('\r',x+1);
if((y<x)||((z>x)&&(z<y)))
y=z;
if(y>x)
return wholeText.substring(0,x)+fullNewLine+wholeText.substring(y);
}
return wholeText;
}
protected String findString(final Modifiable E, final List<String> ignoreStats, final String defPrefix, String tagName, XMLTag piece, final Map<String,Object> defined) throws CMException,PostProcessException
{
tagName=tagName.toUpperCase().trim();
if(tagName.startsWith("SYSTEM_RANDOM_NAME:"))
{
final String[] split=tagName.substring(19).split("-");
if((split.length==2)&&(CMath.isInteger(split[0]))&&(CMath.isInteger(split[1])))
return CMLib.login().generateRandomName(CMath.s_int(split[0]), CMath.s_int(split[1]));
throw new CMException("Bad random name range in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
else
if(tagName.equals("ROOM_AREAGATE"))
{
if(E instanceof Environmental)
{
final Room R=CMLib.map().roomLocation((Environmental)E);
if(R!=null)
{
boolean foundOne=false;
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
final Room R2=R.getRoomInDir(d);
foundOne=(R2!=null) || foundOne;
if((R2!=null) && (R2.roomID().length()>0) && (R.getArea()!=R2.getArea()))
return CMLib.directions().getDirectionName(d);
}
if(!foundOne)
throw new PostProcessException("No exits at all on on object "+R.roomID()+" in variable '"+tagName+"'");
}
}
return "";
}
if(defPrefix != null)
{
final Object asPreviouslyDefined = defined.get((defPrefix+tagName).toUpperCase());
if(asPreviouslyDefined instanceof String)
return strFilter(E,ignoreStats,defPrefix,(String)asPreviouslyDefined,piece, defined);
}
final String asParm = piece.getParmValue(tagName);
if(asParm != null)
return strFilter(E,ignoreStats,defPrefix,asParm,piece, defined);
final Object asDefined = defined.get(tagName);
if(asDefined instanceof String)
return (String)asDefined;
final String contentload = piece.getParmValue("CONTENT_LOAD");
if((contentload!=null)
&&(contentload.length()>0))
{
final CMFile file = new CMFile(contentload,null,CMFile.FLAG_LOGERRORS|CMFile.FLAG_FORCEALLOW);
if(file.exists() && file.canRead())
return strFilter(E, ignoreStats, defPrefix,file.text().toString(), piece, defined);
else
throw new CMException("Bad content_load filename in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
String questTemplateLoad = piece.getParmValue("QUEST_TEMPLATE_ID");
if((questTemplateLoad!=null)
&&(questTemplateLoad.length()>0))
{
piece.parms().remove("QUEST_TEMPLATE_ID"); // once only, please
questTemplateLoad = strFilter(E,ignoreStats,defPrefix,questTemplateLoad,piece, defined);
final CMFile file = new CMFile(Resources.makeFileResourceName("quests/templates/"+questTemplateLoad.trim()+".quest"),null,CMFile.FLAG_LOGERRORS|CMFile.FLAG_FORCEALLOW);
if(file.exists() && file.canRead())
{
final String rawFileText = file.text().toString();
final int endX=rawFileText.lastIndexOf("#!QUESTMAKER_END_SCRIPT");
if(endX > 0)
{
final int lastCR = rawFileText.indexOf('\n', endX);
final int lastEOF = rawFileText.indexOf('\r', endX);
final int endScript = lastCR > endX ? (lastCR < lastEOF ? lastCR : lastEOF): lastEOF;
final List<String> wizList = Resources.getFileLineVector(new StringBuffer(rawFileText.substring(0, endScript).trim()));
String cleanedFileText = rawFileText.substring(endScript).trim();
cleanedFileText = CMStrings.replaceAll(cleanedFileText, "$#AUTHOR", "CoffeeMud");
final String duration=this.findOptionalString(E, ignoreStats, defPrefix, "DURATION", piece, defined, false);
if((duration != null) && (duration.trim().length()>0))
cleanedFileText = this.replaceLineStartsWithIgnoreCase(cleanedFileText, "set duration", "SET DURATION "+duration);
final String expiration=this.findOptionalString(E, ignoreStats, defPrefix, "EXPIRATION", piece, defined, false);
if((expiration != null) && (expiration.trim().length()>0))
cleanedFileText = this.replaceLineStartsWithIgnoreCase(cleanedFileText, "set duration", "SET EXPIRATION "+expiration);
for(final String wiz : wizList)
{
if(wiz.startsWith("#$"))
{
final int x=wiz.indexOf('=');
if(x>0)
{
final String var=wiz.substring(1,x);
if(cleanedFileText.indexOf(var)>0)
{
final String findVar=wiz.substring(2,x);
final String value=findStringNow(findVar, piece, defined);
cleanedFileText=CMStrings.replaceAll(cleanedFileText,var,value);
}
}
}
}
return cleanedFileText;
}
else
throw new CMException("Corrupt quest_template in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
else
throw new CMException("Bad quest_template_id in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
XMLTag processDefined=null;
if(asDefined instanceof XMLTag)
{
piece=(XMLTag)asDefined;
processDefined=piece;
tagName=piece.tag();
}
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,ignoreStats,defPrefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
throw new CMException("Unable to find tag '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
StringBuffer finalValue = new StringBuffer("");
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final String value=strFilter(E,ignoreStats,defPrefix,valPiece.value(),valPiece, defined);
if(processDefined!=valPiece)
defineReward(E,ignoreStats,defPrefix,valPiece.getParmValue("DEFINE"),valPiece,value,defined,true);
String action = valPiece.getParmValue("ACTION");
if(action==null)
finalValue.append(" ").append(value);
else
{
action=action.toUpperCase().trim();
if((action.length()==0)||(action.equals("APPEND")))
finalValue.append(" ").append(value);
else
if(action.equals("REPLACE"))
finalValue = new StringBuffer(value);
else
if(action.equals("PREPEND"))
finalValue.insert(0,' ').insert(0,value);
else
throw new CMException("Unknown action '"+action+" on subPiece "+valPiece.tag()+" on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
}
final String finalFinalValue=finalValue.toString().trim();
if(processDefined!=null)
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("DEFINE"),processDefined,finalFinalValue,defined,true);
return finalFinalValue;
}
@Override
public String buildQuestScript(final XMLTag piece, final Map<String,Object> defined, final Modifiable E) throws CMException
{
final List<String> ignore=new ArrayList<String>();
try
{
return this.findString(E, ignore, null, "QUEST", piece, defined);
}
catch(final PostProcessException pe)
{
throw new CMException("Post processing not permitted",pe);
}
}
protected Object findObject(final Modifiable E, final List<String> ignoreStats, final String defPrefix, String tagName, XMLTag piece, final Map<String,Object> defined) throws CMException,PostProcessException
{
tagName=tagName.toUpperCase().trim();
if(defPrefix != null)
{
final Object asPreviouslyDefined = defined.get((defPrefix+tagName).toUpperCase());
if(asPreviouslyDefined instanceof String)
return strFilter(E,ignoreStats,defPrefix,(String)asPreviouslyDefined,piece, defined);
if(!(asPreviouslyDefined instanceof XMLTag))
return asPreviouslyDefined;
}
final String asParm = piece.getParmValue(tagName);
if(asParm != null)
return strFilter(E,ignoreStats,defPrefix,asParm,piece, defined);
final Object asDefined = defined.get(tagName);
if((!(asDefined instanceof XMLTag))
&&(!(asDefined instanceof String))
&&(asDefined != null))
return asDefined;
XMLTag processDefined=null;
if(asDefined instanceof XMLTag)
{
piece=(XMLTag)asDefined;
processDefined=piece;
tagName=piece.tag();
}
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,ignoreStats,defPrefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
throw new CMException("Unable to find tag '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final List<Object> finalValues = new ArrayList<Object>();
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final String valueStr=valPiece.value().toUpperCase().trim();
final Object value;
if(valueStr.startsWith("SELECT:"))
{
final List<Map<String,Object>> sel=this.doMQLSelectObjs(E, ignoreStats, defPrefix, valueStr, valPiece, defined);
value=sel;
finalValues.addAll(sel);
}
else
if(valueStr.equals("MOB"))
{
final List<MOB> objs = this.findMobs(E, valPiece, defined, null);
value=objs;
finalValues.addAll(objs);
}
else
if(valueStr.equals("ITEM"))
{
final List<Item> objs = this.findItems(E, valPiece, defined, null);
value=objs;
finalValues.addAll(objs);
}
else
if(valueStr.equals("ABILITY"))
{
final List<Ability> objs = this.findAbilities(E, valPiece, defined, null);
value=objs;
finalValues.addAll(objs);
}
else
{
try
{
final List<Object> objs = parseMQLFrom(valueStr, valueStr, E, ignoreStats, defPrefix, valPiece, defined);
value=objs;
finalValues.addAll(objs);
}
catch(final CMException e)
{
throw new CMException("Unable to produce '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMStrings.limit(piece.value(),100)+":"+e.getMessage());
}
}
if(processDefined!=valPiece)
defineReward(E,ignoreStats,defPrefix,valPiece.getParmValue("DEFINE"),valPiece,value,defined,true);
}
if(processDefined!=null)
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("DEFINE"),processDefined,finalValues.size()==1?finalValues.get(0):finalValues,defined,true);
return finalValues.size()==1?finalValues.get(0):finalValues;
}
protected XMLTag processLikeParm(final String tagName, XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String like = piece.getParmValue("LIKE");
if(like!=null)
{
final List<String> V=CMParms.parseCommas(like,true);
final XMLTag origPiece = piece;
piece=piece.copyOf();
for(int v=0;v<V.size();v++)
{
String s = V.get(v);
if(s.startsWith("$"))
s=s.substring(1).trim();
final XMLTag likePiece =(XMLTag)defined.get(s.toUpperCase().trim());
if((likePiece == null)||(!likePiece.tag().equalsIgnoreCase(tagName)))
throw new CMException("Invalid like: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
piece.contents().addAll(likePiece.contents());
piece.parms().putAll(likePiece.parms());
piece.parms().putAll(origPiece.parms());
}
}
return piece;
}
@Override
public List<XMLTag> getAllChoices(final String tagName, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
return getAllChoices(null,null,null,tagName,piece,defined,true);
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object: "+pe.getMessage(),pe);
}
}
protected List<XMLTag> getAllChoices(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined, final boolean skipTest) throws CMException, PostProcessException
{
if((!skipTest)
&&(!testCondition(E,ignoreStats,defPrefix,CMLib.xml().restoreAngleBrackets(piece.getParmValue("CONDITION")),piece,defined)))
return new Vector<XMLTag>(1);
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("PREDEFINE"),piece,piece.value(),defined,false); // does pre-define
final List<XMLTag> choices = new Vector<XMLTag>();
final String inserter = piece.getParmValue("INSERT");
if(inserter != null)
{
final String upperInserter = inserter.toUpperCase().trim();
if(upperInserter.startsWith("SELECT:"))
{
final List<Map<String,Object>> objs=this.doMQLSelectObjs(E, ignoreStats, defPrefix, upperInserter, piece, defined);
for(final Map<String,Object> m : objs)
{
for(final String key : m.keySet())
{
if(key.equalsIgnoreCase(tagName))
choices.add(CMLib.xml().createNewTag(tagName, this.convertMQLObjectToString(m.get(key))));
}
}
}
else
{
final List<String> V=CMParms.parseCommas(upperInserter,true);
for(int v=0;v<V.size();v++)
{
String s = V.get(v);
if(s.startsWith("$"))
s=s.substring(1).trim();
final XMLTag insertPiece =(XMLTag)defined.get(s.trim());
if(insertPiece == null)
throw new CMException("Undefined insert: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
if(insertPiece.tag().equalsIgnoreCase(tagName))
choices.addAll(getAllChoices(E,ignoreStats,defPrefix,tagName,insertPiece,defined,false));
}
}
}
else
if(piece.tag().equalsIgnoreCase(tagName))
{
if((piece.parms().containsKey("LAYOUT")) && (piece.tag().equalsIgnoreCase("ROOM")) && (!defined.containsKey("ROOM_LAYOUT")))
return new XVector<XMLTag>(processLikeParm(tagName,piece,defined));
boolean container=false;
for(int p=0;p<piece.contents().size();p++)
{
final XMLTag ppiece=piece.contents().get(p);
if(ppiece.tag().equalsIgnoreCase(tagName))
{
container=true;
break;
}
}
if(!container)
return new XVector<XMLTag>(processLikeParm(tagName,piece,defined));
}
for(int p=0;p<piece.contents().size();p++)
{
final XMLTag subPiece = piece.contents().get(p);
if(subPiece.tag().equalsIgnoreCase(tagName))
choices.addAll(getAllChoices(E,ignoreStats,defPrefix,tagName,subPiece,defined,false));
}
return selectChoices(E,tagName,ignoreStats,defPrefix,choices,piece,defined);
}
protected boolean testCondition(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String condition, final XMLTag piece, final Map<String,Object> defined) throws PostProcessException
{
final Map<String,Object> fixed=new HashMap<String,Object>();
try
{
if(condition == null)
return true;
final List<Varidentifier> ids=parseVariables(condition);
for(final Varidentifier id : ids)
{
try
{
final String upperId=id.var.toUpperCase();
final boolean missingMobVarCondition;
if(defPrefix != null)
{
missingMobVarCondition = (defined!=null)
&&(upperId.startsWith(defPrefix))
&&(!defined.containsKey(upperId));
if(missingMobVarCondition)
{
XMLTag newPiece=piece;
while((newPiece.parent()!=null)&&(newPiece.tag().equals(piece.tag())))
newPiece=newPiece.parent();
fillOutStatCode(E, ignoreStats, defPrefix, id.var.substring(defPrefix.length()), newPiece, defined, false);
}
}
else
missingMobVarCondition = false;
String value;
if(upperId.startsWith("SELECT:"))
{
try
{
value=doMQLSelectString(E,null,null,id.var,piece,defined);
}
catch(final MQLException e)
{
value="";
}
return this.testCondition(E, ignoreStats, defPrefix, CMStrings.replaceAll(condition, condition.substring(id.outerStart,id.outerEnd), value), piece, defined);
}
else
value=findString(E,ignoreStats,defPrefix,id.var, piece, defined);
if(CMath.isMathExpression(value))
{
final String origValue = value;
final double val=CMath.parseMathExpression(value);
if(Math.round(val)==val)
value=""+Math.round(val);
else
value=""+val;
if((origValue.indexOf('?')>0) // random levels need to be chosen ONCE, esp when name is involved.
&&(missingMobVarCondition)
&&(defined != null))
defined.put(upperId,value);
}
fixed.put(id.var.toUpperCase(),value);
}
catch(final CMException e)
{
}
}
fixed.putAll(defined);
final boolean test= CMStrings.parseStringExpression(condition.toUpperCase(),fixed, true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","TEST "+piece.tag()+": "+condition+"="+test);
return test;
}
catch(final Exception e)
{
if(e instanceof PostProcessException)
throw (PostProcessException)e;
Log.errOut("Generate",e.getMessage()+": "+condition);
try {
CMStrings.parseStringExpression(condition,fixed, true);
}
catch(final Exception e1)
{
}
return false;
}
}
protected String getRequirementsDescription(final String values)
{
if(values==null)
return "";
if(values.equalsIgnoreCase("integer")||values.equalsIgnoreCase("int"))
return " as an integer or integer expression";
else
if(values.equalsIgnoreCase("double")||values.equalsIgnoreCase("#")||values.equalsIgnoreCase("number"))
return " as a number or numeric expression";
else
if(values.equalsIgnoreCase("string")||values.equalsIgnoreCase("$"))
return " as an open string";
else
if(values.trim().length()>0)
return " as one of the following values: "+values;
return "";
}
protected boolean checkRequirementsValue(final String validValue, final String value)
{
if(validValue==null)
return value != null;
if(validValue.equalsIgnoreCase("integer")||validValue.equalsIgnoreCase("int"))
return CMath.isMathExpression(value);
else
if(validValue.equalsIgnoreCase("double")||validValue.equalsIgnoreCase("#")||validValue.equalsIgnoreCase("number"))
return CMath.isMathExpression(value);
else
if(validValue.equalsIgnoreCase("string")||validValue.equalsIgnoreCase("$"))
return value.length()>0;
else
if(validValue.trim().length()>0)
return CMParms.containsIgnoreCase(CMParms.toStringArray(CMParms.parseSemicolons(validValue,true)),value);
return value.length()==0;
}
protected String cleanRequirementsValue(final String values, final String value)
{
if(values==null)
return value;
if(values.equalsIgnoreCase("integer")||values.equalsIgnoreCase("int"))
return Integer.toString(CMath.s_parseIntExpression(value));
else
if(values.equalsIgnoreCase("double")||values.equalsIgnoreCase("#")||values.equalsIgnoreCase("number"))
return Double.toString(CMath.s_parseMathExpression(value));
else
if(values.equalsIgnoreCase("string")||values.equalsIgnoreCase("$"))
return value;
else
if(values.trim().length()>0)
{
final String[] arrayStr=CMParms.toStringArray(CMParms.parseSemicolons(values,true));
int x=CMParms.indexOfIgnoreCase(arrayStr,value);
if(x<0)
x=0;
return arrayStr[x];
}
return value;
}
@Override
public Map<String,String> getUnfilledRequirements(final Map<String,Object> defined, final XMLTag piece)
{
String requirements = piece.getParmValue("REQUIRES");
final Map<String,String> set=new Hashtable<String,String>();
if(requirements==null)
return set;
requirements = requirements.trim();
final List<String> reqs = CMParms.parseCommas(requirements,true);
for(int r=0;r<reqs.size();r++)
{
String reqVariable=reqs.get(r);
if(reqVariable.startsWith("$"))
reqVariable=reqVariable.substring(1).trim();
String validValues=null;
final int x=reqVariable.indexOf('=');
if(x>=0)
{
validValues=reqVariable.substring(x+1).trim();
reqVariable=reqVariable.substring(0,x).trim();
}
if((!defined.containsKey(reqVariable.toUpperCase()))
||(!checkRequirementsValue(validValues, defined.get(reqVariable.toUpperCase()).toString())))
{
if(validValues==null)
set.put(reqVariable.toUpperCase(), "any");
else
if(validValues.equalsIgnoreCase("integer")||validValues.equalsIgnoreCase("int"))
set.put(reqVariable.toUpperCase(), "int");
else
if(validValues.equalsIgnoreCase("double")||validValues.equalsIgnoreCase("#")||validValues.equalsIgnoreCase("number"))
set.put(reqVariable.toUpperCase(), "double");
else
if(validValues.equalsIgnoreCase("string")||validValues.equalsIgnoreCase("$"))
set.put(reqVariable.toUpperCase(), "string");
else
if(validValues.trim().length()>0)
set.put(reqVariable.toUpperCase(), CMParms.toListString(CMParms.parseSemicolons(validValues,true)));
}
}
return set;
}
protected void checkRequirements(final Map<String,Object> defined, String requirements) throws CMException
{
if(requirements==null)
return;
requirements = requirements.trim();
final List<String> reqs = CMParms.parseCommas(requirements,true);
for(int r=0;r<reqs.size();r++)
{
String reqVariable=reqs.get(r);
if(reqVariable.startsWith("$"))
reqVariable=reqVariable.substring(1).trim();
String validValues=null;
final int x=reqVariable.indexOf('=');
if(x>=0)
{
validValues=reqVariable.substring(x+1).trim();
reqVariable=reqVariable.substring(0,x).trim();
}
if(!defined.containsKey(reqVariable.toUpperCase()))
throw new CMException("Required variable not defined: '"+reqVariable+"'. Please define this variable"+getRequirementsDescription(validValues)+".");
if(!checkRequirementsValue(validValues, defined.get(reqVariable.toUpperCase()).toString()))
throw new CMException("The required variable '"+reqVariable+"' is not properly defined. Please define this variable"+getRequirementsDescription(validValues)+".");
}
}
@Override
public void checkRequirements(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
checkRequirements(defined,piece.getParmValue("REQUIRES"));
}
protected List<XMLTag> selectChoices(final Modifiable E, final String tagName, final List<String> ignoreStats, final String defPrefix, final List<XMLTag> choices, final XMLTag piece, final Map<String,Object> defined) throws CMException, PostProcessException
{
String selection = piece.getParmValue("SELECT");
if(selection == null)
return choices;
selection=selection.toUpperCase().trim();
List<XMLLibrary.XMLTag> selectedChoicesV=null;
if(selection.equals("NONE"))
selectedChoicesV= new Vector<XMLTag>();
else
if(selection.equals("ALL"))
selectedChoicesV=choices;
else
if((choices.size()==0)
&&(!selection.startsWith("ANY-0"))
&&(!selection.startsWith("FIRST-0"))
&&(!selection.startsWith("LAST-0"))
&&(!selection.startsWith("PICK-0"))
&&(!selection.startsWith("LIMIT-")))
{
throw new CMException("Can't make selection among NONE: on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
else
if(selection.equals("FIRST"))
selectedChoicesV= new XVector<XMLTag>(choices.get(0));
else
if(selection.startsWith("FIRST-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick first "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
for(int v=0;v<num;v++)
selectedChoicesV.add(choices.get(v));
}
else
if(selection.startsWith("LIMIT-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if(num<0)
throw new CMException("Can't pick limit "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
if(choices.size()<=num)
selectedChoicesV.addAll(choices);
else
while(selectedChoicesV.size()<num)
selectedChoicesV.add(choices.remove(CMLib.dice().roll(1, choices.size(), -1)));
}
else
if(selection.equals("LAST"))
selectedChoicesV=new XVector<XMLTag>(choices.get(choices.size()-1));
else
if(selection.startsWith("LAST-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick last "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
for(int v=choices.size()-num;v<choices.size();v++)
selectedChoicesV.add(choices.get(v));
}
else
if(selection.startsWith("PICK-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
final List<Integer> wV=new XArrayList<Integer>(choices.size(),true);
for(int c=0;c<cV.size();c++)
{
final XMLTag lilP=cV.get(c);
final String pickWeight=lilP.getParmValue("PICKWEIGHT");
final int weight;
if(pickWeight==null)
weight=0;
else
{
final String weightValue=strFilterNow(E,ignoreStats,defPrefix,pickWeight,piece, defined);
weight=CMath.s_parseIntExpression(weightValue);
}
if(weight < 0)
{
cV.remove(c);
c--;
}
else
{
wV.add(Integer.valueOf(weight));
}
}
for(int v=0;v<num;v++)
{
int total=0;
for(int c=0;c<cV.size();c++)
total += wV.get(c).intValue();
if(total==0)
{
if(cV.size()>0)
{
final int c=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(c));
cV.remove(c);
wV.remove(c);
}
}
else
{
int choice=CMLib.dice().roll(1,total,0);
int c=-1;
while(choice>0)
{
c++;
choice-=wV.get(c).intValue();
}
if((c>=0)&&(c<cV.size()))
{
selectedChoicesV.add(cV.get(c));
cV.remove(c);
wV.remove(c);
}
}
}
}
else
if(selection.equals("ANY"))
selectedChoicesV=new XVector<XMLTag>(choices.get(CMLib.dice().roll(1,choices.size(),-1)));
else
if(selection.startsWith("ANY-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick last "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
for(int v=0;v<num;v++)
{
final int x=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(x));
cV.remove(x);
}
}
else
if(selection.startsWith("REPEAT-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if(num<0)
throw new CMException("Can't pick last "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
for(int v=0;v<num;v++)
{
final int x=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(x));
}
}
else
if((selection.trim().length()>0)&&CMath.isMathExpression(selection))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick any "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
for(int v=0;v<num;v++)
{
final int x=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(x));
cV.remove(x);
}
}
else
throw new CMException("Illegal select type '"+selection+"' on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
return selectedChoicesV;
}
protected String strFilterNow(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
return strFilter(E,ignoreStats,defPrefix,str,piece,defined);
}
catch(final PostProcessException pe)
{
throw new CMException("Post processing not permitted",pe);
}
}
private static enum SelectMQLState
{
STATE_SELECT0, // name
STATE_SELECT1, // as or from or ,
STATE_AS0, // as
STATE_AS1, // expect from or , ONLY
STATE_FROM0, // loc
STATE_FROM1, // paren
STATE_EXPECTWHEREOREND, // expect where
STATE_WHERE0, // object
STATE_WHERE1, // comparator
STATE_WHERE2, // object rhs
STATE_EXPECTCONNOREND, // expect connector or end of clause
STATE_WHEREEMBEDLEFT0, // got ( on left of comparator
STATE_WHEREEMBEDRIGHT0, // got ( on right of comparator
STATE_EXPECTNOTHING // end of where clause
}
/**
* Class for semi-parsed MQLClause, including method
* to do the parsig to fill out this object
*
* @author Bo Zimmerman
*
*/
private static class MQLClause
{
/**
* Connector descriptors for connecting mql where clauses together
* @author Bo Zimmerman
*
*/
private static enum WhereConnector { ENDCLAUSE, AND, OR }
/**
* Connector descriptors for connecting mql where clauses together
* @author Bo Zimmerman
*
*/
private static enum WhereComparator { EQ, NEQ, GT, LT, GTEQ, LTEQ, LIKE, IN, NOTLIKE, NOTIN }
/** An abstract Where Clause
* @author Bo Zimmerman
*
*/
private static class WhereComp
{
private String lhs = null;
private WhereComparator comp = null;
private String rhs = null;
}
private static class WhereClause
{
private WhereClause prev = null;
private WhereClause parent = null;
private WhereClause child = null;
private WhereComp lhs = null;
private WhereConnector conn = null;
private WhereClause next = null;
}
private enum AggregatorFunctions
{
COUNT,
MEDIAN,
MEAN,
UNIQUE,
FIRST,
ANY
}
private static class WhatBit extends Pair<String,String>
{
private WhatBit(final String what, final String as)
{
super(what,as);
}
private String what()
{
return first;
}
private String as()
{
return second;
}
@Override
public String toString()
{
if(first.equals(second))
return first;
return first+" as "+second;
}
}
private String mql = "";
private final List<WhatBit> what = new ArrayList<WhatBit>(1);
private String from = "";
private WhereClause wheres = null;
private boolean isTermProperlyEnded(final StringBuilder curr)
{
if(curr.length()<2)
return true;
if((curr.charAt(0)=='\"')
||(curr.charAt(0)=='\''))
{
final int endDex=curr.length()-1;
if(curr.charAt(endDex) != curr.charAt(0))
return false;
if((curr.length()>2)&&(curr.charAt(endDex-1)=='\\'))
return false;
}
return true;
}
/**
* parse the mql statement into this object
*
* @param str the original mql statement
* @param mqlbits mql statement, minus select: must be ALL UPPERCASE
* @throws CMException
*/
private void parseMQL(final String str, final String mqlbits) throws MQLException
{
this.mql=str;
final StringBuilder curr=new StringBuilder("");
int pdepth=0;
WhereClause wheres = new WhereClause();
this.wheres=wheres;
WhereComp wcomp = new WhereComp();
SelectMQLState state=SelectMQLState.STATE_SELECT0;
for(int i=0;i<=mqlbits.length();i++)
{
final char c=(i==mqlbits.length())?' ':mqlbits.charAt(i);
switch(state)
{
case STATE_SELECT0: // select state
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
// we just got a name symbol, so go to state 1 and expect AS or FROM or ,
what.add(new WhatBit(curr.toString(),curr.toString()));
state=SelectMQLState.STATE_SELECT1;
curr.setLength(0);
}
else
curr.append(c);
}
}
else
if(c==',')
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
what.add(new WhatBit(curr.toString(),curr.toString()));
curr.setLength(0);
}
else
curr.append(c);
}
else
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_SELECT1: // expect AS or FROM or ,
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(curr.toString().equals("FROM"))
{
curr.setLength(0);
state=SelectMQLState.STATE_FROM0;
}
else
if(curr.toString().equals("AS"))
{
curr.setLength(0);
state=SelectMQLState.STATE_AS0;
}
else
throw new MQLException("Unexpected select string in Malformed mql: "+str);
}
}
else
if(c==',')
{
if(curr.length()==0)
state=SelectMQLState.STATE_SELECT0;
else
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_AS0: // as name
{
if(Character.isWhitespace(c)
||(c==','))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
if(curr.toString().equals("FROM"))
throw new MQLException("Unexpected FROM in Malformed mql: "+str);
else
if(curr.toString().equals("AS"))
throw new MQLException("Unexpected AS in Malformed mql: "+str);
else
{
state=SelectMQLState.STATE_AS1; // expect from or , ONLY
what.get(what.size()-1).second = curr.toString();
curr.setLength(0);
}
}
else
curr.append(c);
}
else
if(c==',')
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_AS1: // expect FROM or , only
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(curr.toString().equals("FROM"))
{
curr.setLength(0);
state=SelectMQLState.STATE_FROM0;
}
else
throw new MQLException("Unexpected name string in Malformed mql: "+str);
}
}
else
if(c==',')
{
if(curr.length()==0)
state=SelectMQLState.STATE_SELECT0;
else
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_FROM0: // from state
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
if(curr.toString().equals("WHERE"))
throw new MQLException("Unexpected WHERE in Malformed mql: "+str);
else
{
from=curr.toString();
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTWHEREOREND; // now expect where
}
}
else
curr.append(c);
}
}
else
if(c=='(')
{
if(curr.length()==0)
state=SelectMQLState.STATE_FROM1;
else
throw new MQLException("Unexpected ( in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_FROM1: // from () state
{
if(c=='(')
pdepth++;
else
if(c==')')
{
if(pdepth==0)
{
from=curr.toString();
state=SelectMQLState.STATE_EXPECTWHEREOREND; // expect where
curr.setLength(0);
}
else
pdepth--;
}
else
curr.append(c);
break;
}
case STATE_EXPECTWHEREOREND: // expect where clause
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(curr.toString().equals(";"))
{
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTNOTHING;
}
else
if(!curr.toString().equals("WHERE"))
throw new MQLException("Eexpected WHERE in Malformed mql: "+str);
else
{
curr.setLength(0);
state=SelectMQLState.STATE_WHERE0;
}
}
}
else
curr.append(c);
break;
}
case STATE_WHERE0: // initial where state
{
if(Character.isWhitespace(c)
||("<>!=".indexOf(c)>=0))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
wcomp=new WhereComp();
if((wheres.lhs!=null)
||(wheres.parent!=null))
{
final WhereClause newClause = new WhereClause();
newClause.prev=wheres;
wheres.next=newClause;
wheres=newClause;
}
wheres.lhs=wcomp;
wcomp.lhs = curr.toString();
curr.setLength(0);
if(!Character.isWhitespace(c))
curr.append(c);
state=SelectMQLState.STATE_WHERE1; // now expect comparator
}
else
curr.append(c);
}
}
else
if(c=='(')
{
if(curr.length()==0)
state=SelectMQLState.STATE_WHEREEMBEDLEFT0;
else
throw new MQLException("Unexpected ( in Malformed mql: "+str);
}
else
if(c==')')
throw new MQLException("Unexpected ) in Malformed mql: "+str);
else
curr.append(c);
break;
}
case STATE_WHEREEMBEDLEFT0:
{
if(c=='(')
{
if(curr.length()==0)
{
final WhereClause priorityClause = new WhereClause();
if((wheres.lhs!=null)
||(wheres.parent!=null)
||(wheres.conn!=null))
{
final WhereClause dummyClause = new WhereClause();
wheres.next=dummyClause;
dummyClause.prev=wheres;
wheres=dummyClause;
}
priorityClause.child=wheres;
wheres.parent=priorityClause;
wheres=priorityClause;
i--;
state=SelectMQLState.STATE_WHERE0; // expect lhs of a comp
}
else
pdepth++;
}
else
if(c==')')
{
if(pdepth==0)
{
wcomp=new WhereComp();
if((wheres.lhs!=null)
||(wheres.parent!=null)
||(wheres.conn!=null))
{
final WhereClause newClause = new WhereClause();
wheres.next=newClause;
newClause.prev=wheres;
wheres=newClause;
}
wheres.lhs=wcomp;
wcomp.lhs=curr.toString();
state=SelectMQLState.STATE_WHERE1; // expect connector or endofclause
curr.setLength(0);
}
else
pdepth--;
}
else
if(Character.isWhitespace(c) && (curr.length()==0))
{}
else
{
curr.append(c);
if((curr.length()<8)
&&(!"SELECT:".startsWith(curr.toString())))
{
final WhereClause priorityClause = new WhereClause();
if((wheres.lhs!=null)
||(wheres.parent!=null)
||(wheres.conn!=null))
{
final WhereClause dummyClause = new WhereClause();
wheres.next=dummyClause;
dummyClause.prev=wheres;
wheres=dummyClause;
}
priorityClause.child=wheres;
wheres.parent=priorityClause;
wheres=priorityClause;
i=mqlbits.lastIndexOf('(',i);
curr.setLength(0);
state=SelectMQLState.STATE_WHERE0; // expect lhs of a comp
}
}
break;
}
case STATE_WHERE1: // expect comparator
{
if(curr.length()==0)
{
if(!Character.isWhitespace(c))
curr.append(c);
}
else
{
boolean saveC = false;
boolean done=false;
if("<>!=".indexOf(c)>=0)
{
if("<>!=".indexOf(curr.charAt(0))>=0)
{
curr.append(c);
done=curr.length()>=2;
}
else
throw new MQLException("Unexpected '"+c+"' in Malformed mql: "+str);
}
else
if(!Character.isWhitespace(c))
{
if("<>!=".indexOf(curr.charAt(0))>=0)
{
saveC=true;
done=true;
}
else
curr.append(c);
}
else
done=true;
if(done)
{
final String fcurr=curr.toString();
if(fcurr.equals("="))
{
wcomp.comp=WhereComparator.EQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("!=")||fcurr.equals("<>"))
{
wcomp.comp=WhereComparator.NEQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals(">"))
{
wcomp.comp=WhereComparator.GT;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("<"))
{
wcomp.comp=WhereComparator.LT;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals(">=")||fcurr.equals("=>"))
{
wcomp.comp=WhereComparator.GTEQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("<=")||fcurr.equals("<="))
{
wcomp.comp=WhereComparator.LTEQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("IN"))
{
wcomp.comp=WhereComparator.IN;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("LIKE"))
{
wcomp.comp=WhereComparator.LIKE;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("NOTIN"))
{
wcomp.comp=WhereComparator.NOTIN;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("NOTLIKE"))
{
wcomp.comp=WhereComparator.NOTLIKE;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
throw new MQLException("Unexpected '"+fcurr+"' in Malformed mql: "+str);
if(saveC)
curr.append(c);
}
}
break;
}
case STATE_WHERE2: // where rhs of clause
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
wcomp.rhs=curr.toString();
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTCONNOREND;
}
else
curr.append(c);
}
}
else
if(c==')')
{
if(curr.length()==0)
throw new MQLException("Unexpected ): Malformed mql: "+str);
wcomp.rhs=curr.toString();
curr.setLength(0);
while(wheres.prev!=null)
wheres=wheres.prev;
if(wheres.child==null)
throw new MQLException("Unexpected ): Malformed mql: "+str);
wheres=wheres.child;
state=SelectMQLState.STATE_EXPECTCONNOREND;
}
else
if(c==';')
{
if(curr.length()==0)
throw new MQLException("Unexpected ; in Malformed mql: "+str);
else
{
wcomp.rhs=curr.toString();
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTNOTHING;
}
}
else
if(c=='(')
{
if(curr.length()==0)
state=SelectMQLState.STATE_WHEREEMBEDRIGHT0;
else
throw new MQLException("Unexpected ( in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_WHEREEMBEDRIGHT0:
{
if(c=='(')
{
pdepth++;
}
else
if(c==')')
{
if(pdepth==0)
{
wcomp.rhs=curr.toString();
state=SelectMQLState.STATE_EXPECTCONNOREND; // expect connector or endofclause
curr.setLength(0);
}
else
pdepth--;
}
else
curr.append(c);
break;
}
case STATE_EXPECTCONNOREND: // expect connector or endofclause
{
if(c==';')
{
state=SelectMQLState.STATE_EXPECTNOTHING;
}
else
if(Character.isWhitespace(c) || (c=='('))
{
if(curr.length()>0)
{
if(curr.toString().equals("AND"))
{
wheres.conn = WhereConnector.AND;
state=SelectMQLState.STATE_WHERE0;
curr.setLength(0);
if(c=='(')
i--;
}
else
if(curr.toString().equals("OR"))
{
wheres.conn = WhereConnector.OR;
state=SelectMQLState.STATE_WHERE0;
curr.setLength(0);
if(c=='(')
i--;
}
else
throw new MQLException("Unexpected '"+curr.toString()+"': Malformed mql: "+str);
}
else
if(c=='(')
throw new MQLException("Unexpected ): Malformed mql: "+str);
}
else
if((c==')') && (curr.length()==0))
{
while(wheres.prev!=null)
wheres=wheres.prev;
if(wheres.child==null)
throw new MQLException("Unexpected ): Malformed mql: "+str);
wheres=wheres.child;
}
else
curr.append(c);
break;
}
default:
if(!Character.isWhitespace(c))
throw new MQLException("Unexpected '"+c+"': Malformed mql: "+str);
break;
}
}
if((state != SelectMQLState.STATE_EXPECTNOTHING)
&&(state != SelectMQLState.STATE_EXPECTWHEREOREND)
&&(state != SelectMQLState.STATE_EXPECTCONNOREND))
throw new MQLException("Unpected end of clause in state "+state.toString()+" in mql: "+str);
}
}
protected void doneWithMQLObject(final Object o)
{
if(o instanceof Physical)
{
final Physical P=(Physical)o;
if(!P.isSavable())
{
if((P instanceof DBIdentifiable)
&&(((DBIdentifiable)P).databaseID().equals("DELETE")))
P.destroy();
else
if((P instanceof Area)
&&(((Area)P).getAreaState()==Area.State.STOPPED))
P.destroy();
else
if((P instanceof Room)
&&(((Room)P).getArea().amDestroyed()))
P.destroy();
}
}
}
protected List<Object> parseMQLCMFile(final CMFile F, final String mql) throws MQLException
{
final List<Object> from=new LinkedList<Object>();
String str=F.text().toString().trim();
// normalize singletons
if(str.startsWith("<MOB>"))
str="<MOBS>"+str+"</MOB>";
else
if(str.startsWith("<ITEM>"))
str="<ITEMS>"+str+"</ITEMS>";
else
if(str.startsWith("<AREA>"))
str="<AREAS>"+str+"</AREAS>";
if(str.startsWith("<MOBS>"))
{
final List<MOB> mobList=new LinkedList<MOB>();
final String err = CMLib.coffeeMaker().addMOBsFromXML(str, mobList, null);
if((err!=null)&&(err.length()>0))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed mob parsing '"+err+"' in "+mql);
for(final MOB M : mobList)
{
CMLib.threads().deleteAllTicks(M);
M.setSavable(false);
M.setDatabaseID("DELETE");
}
from.addAll(mobList);
}
else
if(str.startsWith("<ITEMS>"))
{
final List<Item> itemList=new LinkedList<Item>();
final String err = CMLib.coffeeMaker().addItemsFromXML(str, itemList, null);
if((err!=null)&&(err.length()>0))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed item parsing '"+err+"' in "+mql);
for(final Item I : itemList)
{
CMLib.threads().deleteAllTicks(I);
I.setSavable(false);
I.setDatabaseID("DELETE");
}
from.addAll(itemList);
}
else
if(str.startsWith("<AREAS>"))
{
final List<Area> areaList=new LinkedList<Area>();
final List<List<XMLLibrary.XMLTag>> areas=new ArrayList<List<XMLLibrary.XMLTag>>();
String err=CMLib.coffeeMaker().fillAreasVectorFromXML(str,areas,null,null);
if((err!=null)&&(err.length()>0))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed area parsing '"+err+"' in "+mql);
for(final List<XMLLibrary.XMLTag> area : areas)
err=CMLib.coffeeMaker().unpackAreaFromXML(area, null, null, true, false);
for(final Area A : areaList)
{
CMLib.threads().deleteAllTicks(A);
A.setSavable(false);
A.setAreaState(State.STOPPED);
}
from.addAll(areaList);
}
else
if(str.startsWith("<AROOM>"))
{
final List<Room> roomList=new LinkedList<Room>();
final Area dumbArea=CMClass.getAreaType("StdArea");
CMLib.flags().setSavable(dumbArea, false);
final List<XMLLibrary.XMLTag> tags=CMLib.xml().parseAllXML(str);
final String err=CMLib.coffeeMaker().unpackRoomFromXML(dumbArea, tags, true, false);
if((err!=null)&&(err.length()>0)||(!dumbArea.getProperMap().hasMoreElements()))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed room parsing '"+err+"' in "+mql);
roomList.add(dumbArea.getProperMap().nextElement());
for(final Room R : roomList)
{
CMLib.threads().deleteAllTicks(R);
dumbArea.delProperRoom(R);
R.setSavable(false);
}
dumbArea.destroy();
from.addAll(roomList);
}
else
throw new MQLException("CMFile "+F.getAbsolutePath()+" not selectable from in "+mql);
return from;
}
protected List<Object> flattenMQLObjectList(final Collection<Object> from)
{
final List<Object> flat=new LinkedList<Object>();
for(final Object o1 : from)
{
if((o1 instanceof CMObject)
||(o1 instanceof String))
flat.add(o1);
else
if(o1 instanceof List)
{
@SuppressWarnings("unchecked")
final List<Object> nl = (List<Object>)o1;
flat.addAll(flattenMQLObjectList(nl));
}
else
if(o1 instanceof Map)
{
@SuppressWarnings("unchecked")
final Map<Object,Object> m=(Map<Object,Object>)o1;
flat.addAll(flattenMQLObjectList(m.values()));
}
else
flat.add(o1);
}
return flat;
}
protected List<Object> parseMQLFrom(final String fromClause, final String mql, final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Object> from=new LinkedList<Object>();
if(fromClause.startsWith("SELECT:"))
{
from.addAll(doMQLSelectObjs(E, ignoreStats, defPrefix, fromClause, piece, defined));
return from;
}
for(final String f : fromClause.split("\\\\"))
{
if(f.startsWith("/")
|| f.startsWith("::")
|| f.startsWith("//"))
{
final CMFile F=new CMFile(f,null);
if(!F.exists())
throw new MQLException("CMFile "+f+" not found in "+mql);
if(F.isDirectory())
{
for(final CMFile F2 : F.listFiles())
{
if(!F2.isDirectory())
from.addAll(this.parseMQLCMFile(F, mql));
}
}
else
from.addAll(this.parseMQLCMFile(F, mql));
}
else
if(f.equals("AREAS")
||((from.size()>0)&&(f.equals("AREA"))))
{
if(from.size()==0)
from.addAll(new XVector<Area>(CMLib.map().areas()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
final Area A;
if (o instanceof CMObject)
A=CMLib.map().areaLocation((CMObject)o);
else
A=null;
if(A==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(!from.contains(A))
from.add(A);
}
}
}
else
if(f.equals("AREA") && (from.size()==0))
{
final Area A=(E instanceof Environmental) ? CMLib.map().areaLocation(E) : null;
if(A==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(A))
from.add(A);
}
else
if(f.equals("ROOMS")
||((from.size()>0)&&(f.equals("ROOM"))))
{
if(from.size()==0)
from.addAll(new XVector<Room>(CMLib.map().rooms()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
final Room R;
if(o instanceof Area)
{
from.addAll(new XVector<Room>(((Area)o).getProperMap()));
continue;
}
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(!from.contains(R))
from.add(R);
}
}
}
else
if(f.equals("ROOM") && (from.size()==0))
{
final Room R=(E instanceof Environmental) ? CMLib.map().roomLocation((Environmental)E) : null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(R))
from.add(R);
}
else
if((f.equals("PLAYERS"))
||((from.size()>0)&&(f.equals("PLAYER"))))
{
if(from.size()==0)
{
final Enumeration<Session> sesss = new IteratorEnumeration<Session>(CMLib.sessions().allIterableAllHosts().iterator());
final Enumeration<MOB> m=new FilteredEnumeration<MOB>(new ConvertingEnumeration<Session, MOB>(sesss, sessionToMobConvereter), noMobFilter);
for(;m.hasMoreElements();)
from.add(m.nextElement());
}
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
final Enumeration<Session> sesss = new IteratorEnumeration<Session>(CMLib.sessions().allIterableAllHosts().iterator());
final Enumeration<MOB> m=new FilteredEnumeration<MOB>(new ConvertingEnumeration<Session, MOB>(sesss, sessionToMobConvereter), noMobFilter);
for(;m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(CMLib.map().areaLocation(M) == o)
from.add(M);
}
}
else
if(o instanceof Room)
{
for(final Enumeration<MOB> m=((Room)o).inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)
&&(M.isPlayer()))
from.add(M);
}
}
if(o instanceof MOB)
{
if(((MOB)o).isPlayer())
from.add(o);
}
else
if(o instanceof Item)
{
final Item I=(Item)o;
if((I.owner() instanceof MOB)
&&(((MOB)I.owner())).isPlayer())
from.add(I.owner());
}
else
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
}
}
}
else
if(f.equals("PLAYER") && (from.size()==0))
{
final MOB oE=(E instanceof MOB) ? (MOB)E : null;
if((oE==null)||(!oE.isPlayer()))
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("MOBS")
||((from.size()>0)&&(f.equals("MOB"))))
{
if(from.size()==0)
from.addAll(new XVector<MOB>(CMLib.map().worldMobs()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(!from.contains(M))
from.add(M);
}
}
}
}
else
if((o instanceof MOB)&&(f.equals("MOB")))
from.add(o);
else
{
final Room R;
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(!from.contains(M))
from.add(M);
}
}
}
}
}
}
else
if(f.equals("MOB") && (from.size()==0))
{
final Environmental oE=(E instanceof MOB) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("NPCS")
||((from.size()>0)&&(f.equals("NPC"))))
{
if(from.size()==0)
from.addAll(new XVector<MOB>(new FilteredEnumeration<MOB>(CMLib.map().worldMobs(),npcFilter)));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(npcFilter.passesFilter(M) && (!from.contains(M)))
from.add(M);
}
}
}
}
else
if((o instanceof MOB)
&&(f.equals("NPC"))
&&(npcFilter.passesFilter((MOB)o)))
from.add(o);
else
{
final Room R;
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(npcFilter.passesFilter(M) && (!from.contains(M)))
from.add(M);
}
}
}
}
}
}
else
if(f.equals("NPC") && (from.size()==0))
{
final MOB oE=(E instanceof MOB) ? (MOB)E : null;
if((oE==null) || (oE.isPlayer()))
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("ITEMS")
||((from.size()>0)&&(f.equals("ITEM"))))
{
if(from.size()==0)
from.addAll(new XVector<Item>(CMLib.map().worldEveryItems()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
from.addAll(new XVector<Item>(r.nextElement().itemsRecursive()));
}
else
if((o instanceof Item)
&&(f.equals("ITEM")))
from.add(o);
else
{
final Room R;
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
from.addAll(new XVector<Item>(R.itemsRecursive()));
}
}
}
}
else
if(f.equals("ITEM") && (from.size()==0))
{
final Environmental oE=(E instanceof Item) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("EQUIPMENT"))
{
if(from.size()==0)
{
final Environmental oE=(E instanceof MOB) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
{
for(final Enumeration<Item> i=((MOB)oE).items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
}
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<MOB> m=r.nextElement().inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
}
}
else
if(o instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)o).items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
else
if(o instanceof Room)
{
for(final Enumeration<MOB> m=((Room)o).inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
}
else
if(o instanceof Item)
{
if(((Item)o).amBeingWornProperly())
from.add(o);
}
else
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
}
}
}
else
if(f.equals("OWNER"))
{
if(from.size()==0)
{
final Environmental oE=(E instanceof Item) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(((Item)E).owner()!=null)
from.add(((Item)E).owner());
}
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<MOB> m=r.nextElement().inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.owner()!=null)
&&(!from.contains(I.owner())))
from.add(I.owner());
}
}
}
}
else
if(o instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)o).items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.owner()!=null)
&&(!from.contains(I.owner())))
from.add(I.owner());
}
}
else
if(o instanceof Room)
{
for(final Enumeration<MOB> m=((Room)o).inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.owner()!=null)
&&(!from.contains(I.owner())))
from.add(I.owner());
}
}
}
else
if(o instanceof Item)
{
if(((Item)o).amBeingWornProperly())
from.add(o);
}
else
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
}
}
}
else
if(f.startsWith("$"))
{
final Object val = defined.get(f.substring(1));
if(val == null)
throw new MQLException("Unknown from clause selector '"+f+"' in "+mql);
if(val instanceof XMLTag)
{
final XMLTag tag=(XMLTag)val;
try
{
if(tag.tag().equalsIgnoreCase("STRING"))
from.add(findString(E,ignoreStats,defPrefix,"STRING",(XMLTag)val,defined));
else
{
final Object o =findObject(E,ignoreStats,defPrefix,"OBJECT",tag,defined);
if(o instanceof List)
{
@SuppressWarnings({ "unchecked" })
final List<Object> l=(List<Object>)o;
from.addAll(l);
}
else
from.add(o);
}
}
catch(final CMException e)
{
throw new MQLException(e.getMessage(),e);
}
}
else
from.add(val);
}
else
{
final Object asDefined = defined.get(f);
if(asDefined == null)
throw new MQLException("Unknown from clause selector '"+f+"' in "+mql);
if(asDefined instanceof List)
from.addAll((from));
else
from.add(asDefined);
}
}
return from;
}
protected Object getSimpleMQLValue(final String valueName, final Object from)
{
if(valueName.equals(".")||valueName.equals("*"))
return from;
if(from instanceof Map)
{
@SuppressWarnings({ "unchecked" })
final Map<String,Object> m=(Map<String,Object>)from;
if(m.containsKey(valueName))
return m.get(valueName);
for(final String key : m.keySet())
{
final Object o=m.get(key);
if(o instanceof CMObject)
return getSimpleMQLValue(valueName,o);
}
}
if(from instanceof List)
{
@SuppressWarnings("rawtypes")
final List l=(List)from;
if(l.size()>0)
return getSimpleMQLValue(valueName,l.get(0));
}
if(from instanceof MOB)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Item)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Room)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Area)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Modifiable)
{
return ((Modifiable)from).getStat(valueName);
}
return null;
}
protected Object getFinalMQLValue(final String strpath, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
if(strpath.startsWith("SELECT:"))
{
if(from instanceof Modifiable)
return doMQLSelectObjs((Modifiable)from,ignoreStats,defPrefix,strpath,piece,defined);
else
return doMQLSelectObjs(E,ignoreStats,defPrefix,strpath,piece,defined);
}
Object finalO=null;
try
{
int index=0;
final String[] strs=CMStrings.replaceAll(strpath,"\\\\","\\").split("\\\\");
for(final String str : strs)
{
index++;
if(str.equals("*")||str.equals("."))
{
if(finalO==null)
finalO=from;
}
else
if(CMath.isNumber(str.trim()) || (str.trim().length()==0))
finalO=str.trim();
else
if(str.startsWith("\"")&&(str.endsWith("\""))&&(str.length()>1))
finalO=this.strFilter(E, ignoreStats, defPrefix, CMStrings.replaceAll(str.substring(1,str.length()-1),"\\\"","\""), piece, defined);
else
if(str.startsWith("'")&&(str.endsWith("'"))&&(str.length()>1))
finalO=this.strFilter(E, ignoreStats, defPrefix, CMStrings.replaceAll(str.substring(1,str.length()-1),"\\'","'"), piece, defined);
else
if(str.startsWith("`")&&(str.endsWith("`"))&&(str.length()>1))
finalO=this.strFilter(E, ignoreStats, defPrefix, CMStrings.replaceAll(str.substring(1,str.length()-1),"\\`","`"), piece, defined);
else
if(str.startsWith("COUNT"))
{
Object chkO=finalO;
if(chkO==null)
chkO=from;
if(chkO==null)
throw new MQLException("Can not count instances of null in '"+strpath+"'");
else
if(chkO instanceof List)
{
@SuppressWarnings("rawtypes")
final List l=(List)chkO;
chkO=""+l.size();
}
else
if((chkO instanceof String)
||(chkO instanceof Environmental))
{
if(index>1)
{
final StringBuilder whatBuilder=new StringBuilder("");
for(int i=0;i<index-1;i++)
whatBuilder.append(strs[i]).append("\\");
final String newWhat=whatBuilder.substring(0,whatBuilder.length()-1);
int count=0;
for(final Object o : allFrom)
{
if(o==from)
count++;
else
if(chkO.equals(getFinalMQLValue(newWhat, allFrom, o, E, ignoreStats, defPrefix, piece, defined)))
count++;
}
finalO=""+count;
}
else
finalO=""+allFrom.size();
}
else
finalO="1";
}
else
if(str.startsWith("$"))
{
Object val = defined.get(str.substring(1));
if(val instanceof XMLTag)
{
final XMLTag tag=(XMLTag)val;
if(tag.tag().equalsIgnoreCase("STRING"))
finalO=findString(E,ignoreStats,defPrefix,"STRING",(XMLTag)val,defined);
else
{
final Object o =findObject(E,ignoreStats,defPrefix,"OBJECT",tag,defined);
if(o instanceof Tickable)
CMLib.threads().deleteAllTicks((Tickable)o);
if(o instanceof List)
{
@SuppressWarnings("rawtypes")
final List l=(List)o;
for(final Object o2 : l)
{
if(o2 instanceof Tickable)
CMLib.threads().deleteAllTicks((Tickable)o2);
}
}
val=o;
}
}
if(val == null)
throw new MQLException("Unknown variable '$"+str+"' in str '"+str+"'",new CMException("$"+str));
finalO=val;
}
else
{
final Object fromO=(finalO==null)?from:finalO;
final Object newObj=getSimpleMQLValue(str,fromO);
if(newObj == null)
throw new MQLException("Unknown variable '"+str+"' on '"+fromO+"'",new CMException("$"+str));
finalO=newObj;
}
}
}
catch(final CMException e)
{
if(e instanceof MQLException)
throw (MQLException)e;
else
throw new MQLException("MQL failure on $"+strpath,e);
}
return finalO;
}
protected boolean doMQLComparison(final Object lhso, MQLClause.WhereComparator comp, final Object rhso, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final String lhstr=(lhso==null)?"":lhso.toString();
final String rhstr=(rhso==null)?"":rhso.toString();
if(lhso instanceof List)
{
if(rhso instanceof List)
{
@SuppressWarnings("rawtypes")
final List llhso=(List)lhso;
@SuppressWarnings("rawtypes")
final List lrhso=(List)rhso;
switch(comp)
{
case GT:
return llhso.size()>lrhso.size();
case LT:
return llhso.size()<lrhso.size();
case GTEQ:
if(llhso.size()>lrhso.size())
return true;
comp=MQLClause.WhereComparator.EQ;
break;
case LTEQ:
if(llhso.size()<lrhso.size())
return true;
comp=MQLClause.WhereComparator.EQ;
break;
default:
// see below;
break;
}
switch(comp)
{
case NEQ:
case EQ:
{
if(llhso.size()!=lrhso.size())
return (comp==MQLClause.WhereComparator.NEQ);
boolean allSame=true;
for(final Object o1 : llhso)
{
for(final Object o2 : lrhso)
allSame = allSame || doMQLComparison(o1, MQLClause.WhereComparator.EQ, o2, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
if(allSame)
return (comp==MQLClause.WhereComparator.EQ);
return (comp==MQLClause.WhereComparator.NEQ);
}
case LIKE:
case NOTLIKE:
{
if(llhso.size()!=lrhso.size())
return (comp==MQLClause.WhereComparator.NOTLIKE);
boolean allSame=true;
for(final Object o1 : llhso)
{
for(final Object o2 : lrhso)
allSame = allSame || doMQLComparison(o1, MQLClause.WhereComparator.LIKE, o2, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
if(allSame)
return (comp==MQLClause.WhereComparator.LIKE);
return (comp==MQLClause.WhereComparator.NOTLIKE);
}
case IN:
case NOTIN:
{
boolean allIn=true;
for(final Object o1 : llhso)
allIn = allIn || doMQLComparison(o1, MQLClause.WhereComparator.IN, lrhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
if(allIn)
return (comp==MQLClause.WhereComparator.IN);
return (comp==MQLClause.WhereComparator.NOTIN);
}
default:
// see above:
break;
}
}
else
{
@SuppressWarnings("unchecked")
final List<Object> l=(List<Object>)lhso;
boolean allIn=true;
for(final Object o1 : l)
allIn = allIn && doMQLComparison(o1, comp, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return allIn;
}
}
if((comp != MQLClause.WhereComparator.IN)
&&(comp != MQLClause.WhereComparator.NOTIN))
{
if(rhso instanceof List)
{
@SuppressWarnings("rawtypes")
final List rL=(List)rhso;
if(rL.size()>1)
{
return comp==MQLClause.WhereComparator.NEQ
|| comp==MQLClause.WhereComparator.NOTLIKE
|| comp==MQLClause.WhereComparator.LT
|| comp==MQLClause.WhereComparator.LTEQ;
}
return doMQLComparison(lhso, comp, rL.get(0), allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
if(lhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map mlhso=(Map)lhso;
boolean allSame=true;
for(final Object o1 : mlhso.keySet())
allSame = allSame && doMQLComparison(mlhso.get(o1), comp, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return allSame;
}
else
if(rhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map mrhso=(Map)rhso;
boolean allSame=true;
for(final Object o1 : mrhso.keySet())
allSame = allSame && doMQLComparison(lhso, comp, mrhso.get(o1), allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return allSame;
}
}
switch(comp)
{
case NEQ:
case EQ:
{
final boolean eq=(comp==MQLClause.WhereComparator.EQ);
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return (CMath.s_double(lhstr) == CMath.s_double(rhstr)) == eq;
if(lhso instanceof String)
{
if(rhso instanceof String)
return lhstr.equalsIgnoreCase(rhstr) == eq;
if(rhso instanceof Environmental)
return ((Environmental)rhso).Name().equalsIgnoreCase(lhstr) == eq;
else
return lhstr.equalsIgnoreCase(rhstr) == eq;
}
else
if(rhso instanceof String)
{
if(lhso instanceof Environmental)
return ((Environmental)lhso).Name().equalsIgnoreCase(rhstr) == eq;
else
return rhstr.equalsIgnoreCase(lhstr) == eq;
}
if(lhso instanceof Environmental)
{
if(rhso instanceof Environmental)
return ((Environmental)lhso).sameAs((Environmental)rhso) == eq;
throw new MQLException("'"+rhstr+"' can't be compared to '"+lhstr+"'");
}
else
if(rhso instanceof Environmental)
throw new MQLException("'"+rhstr+"' can't be compared to '"+lhstr+"'");
if((lhso != null)&&(rhso != null))
return (rhso.equals(rhso)) == eq;
else
return (lhso == rhso) == eq;
}
case GT:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) > CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) > 0;
return false; // objects can't be > than each other
case GTEQ:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) >= CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) >= 0;
return doMQLComparison(lhso, MQLClause.WhereComparator.EQ, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
case NOTIN:
case IN:
if(rhso instanceof List)
{
@SuppressWarnings("rawtypes")
final List lrhso=(List)rhso;
for(final Object o2 : lrhso)
{
if(doMQLComparison(lhso, MQLClause.WhereComparator.EQ, o2, allFrom, from,E,ignoreStats,defPrefix,piece,defined))
return comp==(MQLClause.WhereComparator.IN);
}
return comp==(MQLClause.WhereComparator.NOTIN);
}
if(rhso instanceof String)
{
if(lhso instanceof String)
return (rhstr.toUpperCase().indexOf(lhstr.toUpperCase()) >= 0) == (comp==MQLClause.WhereComparator.IN);
else
throw new MQLException("'"+lhstr+"' can't be in a string");
}
if(rhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map m=(Map)rhso;
if(m.containsKey(lhstr.toUpperCase()))
return (comp==MQLClause.WhereComparator.IN);
for(final Object key : m.keySet())
{
if(doMQLComparison(lhso, MQLClause.WhereComparator.EQ, m.get(key), allFrom, from,E,ignoreStats,defPrefix,piece,defined))
return comp==(MQLClause.WhereComparator.IN);
}
}
if(rhso instanceof Environmental)
{
return doMQLComparison(lhso, MQLClause.WhereComparator.EQ, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined)
== (comp==(MQLClause.WhereComparator.IN));
}
throw new MQLException("'"+rhstr+"' can't contain anything");
case NOTLIKE:
case LIKE:
if(!(rhso instanceof String))
throw new MQLException("Nothing can ever be LIKE '"+rhstr+"'");
if(lhso instanceof Environmental)
{
return CMLib.masking().maskCheck(rhstr, (Environmental)lhso, true)
== (comp==MQLClause.WhereComparator.LIKE);
}
if(lhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map m=(Map)lhso;
Object o=m.get("CLASS");
if(!(o instanceof String))
throw new MQLException("'"+lhstr+"' can ever be LIKE anything.");
o=CMClass.getObjectOrPrototype((String)o);
if(o == null)
throw new MQLException("'"+lhstr+"' can ever be LIKE anything but nothing.");
if(!(o instanceof Modifiable))
throw new MQLException("'"+lhstr+"' can ever be LIKE anything modifiable.");
if(!(o instanceof Environmental))
throw new MQLException("'"+lhstr+"' can ever be LIKE anything envronmental.");
final Modifiable mo=(Modifiable)((Modifiable)o).newInstance();
for(final Object key : m.keySet())
{
if((key instanceof String)
&&(m.get(key) instanceof String))
mo.setStat((String)key, (String)m.get(key));
}
if(mo instanceof Environmental)
{
final boolean rv = CMLib.masking().maskCheck(rhstr, (Environmental)lhso, true)
== (comp==MQLClause.WhereComparator.LIKE);
((Environmental)mo).destroy();
return rv;
}
}
else
throw new MQLException("'"+lhstr+"' can ever be LIKE anything at all.");
break;
case LT:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) < CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) < 0;
return false; // objects can't be < than each other
case LTEQ:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) <= CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) <= 0;
return doMQLComparison(lhso, MQLClause.WhereComparator.EQ, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
default:
break;
}
return true;
}
protected boolean doMQLComparison(final MQLClause.WhereComp comp, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final Object lhso=getFinalMQLValue(comp.lhs, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
final Object rhso=getFinalMQLValue(comp.rhs, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return doMQLComparison(lhso, comp.comp, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
protected boolean doMQLWhereClauseFilter(final MQLClause.WhereClause whereClause, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
MQLClause.WhereConnector lastConn=null;
MQLClause.WhereClause clause=whereClause;
boolean result=true;
while(clause != null)
{
boolean thisResult;
if(clause.parent != null)
{
if(clause.lhs != null)
throw new MQLException("Parent & lhs error ");
thisResult=doMQLWhereClauseFilter(clause.parent,allFrom,from,E,ignoreStats,defPrefix,piece,defined);
}
else
if(clause.lhs != null)
thisResult=doMQLComparison(clause.lhs, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
else
if(clause.next != null)
{
if(clause.conn != null)
lastConn=clause.conn;
clause=clause.next;
continue;
}
else
return result;
if(lastConn != null)
{
switch(lastConn)
{
default:
case ENDCLAUSE:
case AND:
result=result&&thisResult;
break;
case OR:
result=result||thisResult;
break;
}
}
else
result=result&&thisResult;
if(clause.conn != null)
{
lastConn=clause.conn;
if(clause.next != null)
{
switch(lastConn)
{
case AND:
if(!result)
return false;
break;
case OR:
if(result)
return true;
break;
default:
case ENDCLAUSE:
break;
}
}
}
clause=clause.next;
}
return result;
}
protected List<Map<String,Object>> doSubObjSelect(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final MQLClause clause, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Map<String,Object>> results=new ArrayList<Map<String,Object>>();
// first estalish the from object
if(clause.from.length()==0)
throw new MQLException("No FROM clause in "+clause.mql);
// froms can have any environmental, or tags
final List<Object> froms=this.parseMQLFrom(clause.from, clause.mql, E, ignoreStats, defPrefix, piece, defined);
final MQLClause.AggregatorFunctions[] aggregates=new MQLClause.AggregatorFunctions[clause.what.size()];
boolean aggregate=false;
for(int i=0;i<clause.what.size();i++)
{
final String w=clause.what.get(i).what();
final int x=w.indexOf('\\');
if(x<0)
continue;
final MQLClause.AggregatorFunctions aggr=(MQLClause.AggregatorFunctions)CMath.s_valueOf(MQLClause.AggregatorFunctions.class, w.substring(0,x));
if(aggr != null)
{
clause.what.get(i).first=w.substring(x+1);
aggregates[i]=aggr;
aggregate=true;
}
}
for(final Object o : froms)
{
if(doMQLWhereClauseFilter(clause.wheres, froms, o,E,ignoreStats,defPrefix,piece,defined))
{
final Map<String,Object> m=new TreeMap<String,Object>();
for(final MQLClause.WhatBit bit : clause.what)
{
final Object o1 = this.getFinalMQLValue(bit.what(), froms, o, E, ignoreStats, defPrefix, piece, defined);
if(o1 instanceof Map)
{
@SuppressWarnings("unchecked")
final Map<String,Object> m2=(Map<String, Object>)o1;
m.putAll(m2);
}
else
m.put(bit.as(), o1);
}
results.add(m);
}
}
if(aggregate)
{
for(int i=0;i<aggregates.length;i++)
{
if(aggregates[i] == null)
continue;
final String whatName=clause.what.get(i).as();
switch(aggregates[i])
{
case COUNT:
{
final String sz=""+results.size();
results.clear();
final Map<String,Object> oneRow=new TreeMap<String,Object>();
results.add(oneRow);
oneRow.put(whatName, sz);
break;
}
case FIRST:
{
if(results.size()>0)
{
final Map<String,Object> first=results.get(0);
results.clear();
results.add(first);
}
break;
}
case ANY:
{
if(results.size()>0)
{
final Map<String,Object> any=results.get(CMLib.dice().roll(1, results.size(), -1));
results.clear();
results.add(any);
}
break;
}
case UNIQUE:
{
final List<Map<String,Object>> nonresults=new ArrayList<Map<String,Object>>(results.size());
nonresults.addAll(results);
results.clear();
final TreeSet<Object> done=new TreeSet<Object>(objComparator);
for(final Map<String,Object> r : results)
{
if(r.containsKey(whatName)
&&(r.get(whatName)!=null)
&&(!done.contains(r.get(whatName))))
{
done.add(r.get(whatName));
results.add(r);
}
}
break;
}
case MEDIAN:
{
final List<Object> allValues=new ArrayList<Object>(results.size());
for(final Map<String,Object> r : results)
{
if(r.containsKey(whatName)&&(r.get(whatName)!=null))
allValues.add(r.get(whatName));
}
Collections.sort(allValues,objComparator);
if(allValues.size()>0)
{
results.clear();
final Map<String,Object> oneRow=new TreeMap<String,Object>();
results.add(oneRow);
oneRow.put(clause.what.get(i).as(), allValues.get((int)Math.round(Math.floor(CMath.div(allValues.size(), 2)))));
}
break;
}
case MEAN:
{
double totalValue=0.0;
for(final Map<String,Object> r : results)
{
if(r.containsKey(whatName)&&(r.get(whatName)!=null))
totalValue += CMath.s_double(r.get(whatName).toString());
}
if(results.size()>0)
{
final String mean=""+(totalValue/results.size());
results.clear();
final Map<String,Object> oneRow=new TreeMap<String,Object>();
results.add(oneRow);
oneRow.put(clause.what.get(i).as(), mean);
}
break;
}
}
}
}
return results;
}
protected String convertMQLObjectToString(final Object o1)
{
if(o1 instanceof MOB)
return CMLib.coffeeMaker().getMobXML((MOB)o1).toString();
else
if(o1 instanceof Item)
return CMLib.coffeeMaker().getItemXML((Item)o1).toString();
else
if(o1 instanceof Ability)
return ((Ability)o1).ID();
else
if(o1 instanceof Room)
return CMLib.map().getExtendedRoomID((Room)o1);
else
if(o1 instanceof Area)
return ((Area)o1).Name();
else
if(o1 instanceof Behavior)
return ((Behavior)o1).ID();
else
if(o1 != null)
return o1.toString();
else
return "";
}
protected List<Map<String,String>> doSubSelectStr(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final MQLClause clause, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Map<String,String>> results=new ArrayList<Map<String,String>>();
final List<Map<String, Object>> objs=this.doSubObjSelect(E, ignoreStats, defPrefix, clause, piece, defined);
for(final Map<String,Object> o : objs)
{
final Map<String,String> n=new TreeMap<String,String>();
results.add(n);
for(final String key : o.keySet())
{
final Object o1=o.get(key);
n.put(key, this.convertMQLObjectToString(o1));
}
}
return results;
}
protected List<Map<String,String>> doMQLSelectStrs(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final int x=str.indexOf(':');
if(x<0)
throw new MQLException("Malformed mql: "+str);
final String mqlbits=str.substring(x+1).toUpperCase();
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("Starting MQL: "+mqlbits);
final MQLClause clause = new MQLClause();
clause.parseMQL(str, mqlbits);
return this.doSubSelectStr(E, ignoreStats, defPrefix, clause, piece, defined);
}
protected List<Map<String,Object>> doMQLSelectObjs(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final int x=str.indexOf(':');
if(x<0)
throw new MQLException("Malformed mql: "+str);
final String mqlbits=str.substring(x+1).toUpperCase();
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("Starting MQL: "+mqlbits);
final MQLClause clause = new MQLClause();
clause.parseMQL(str, mqlbits);
return this.doSubObjSelect(E, ignoreStats, defPrefix, clause, piece, defined);
}
protected String doMQLSelectString(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Map<String,String>> res=doMQLSelectStrs(E,ignoreStats,defPrefix,str,piece,defined);
final StringBuilder finalStr = new StringBuilder("");
for(final Map<String,String> map : res)
{
for(final String key : map.keySet())
finalStr.append(map.get(key)).append(" ");
}
return finalStr.toString().trim();
}
@Override
public String doMQLSelectString(final Modifiable E, final String mql)
{
final Map<String,Object> defined=new TreeMap<String,Object>();
final XMLTag piece=CMLib.xml().createNewTag("tag", "value");
try
{
return doMQLSelectString(E,null,null,mql,piece,defined);
}
catch(final Exception e)
{
final ByteArrayOutputStream bout=new ByteArrayOutputStream();
final PrintStream pw=new PrintStream(bout);
e.printStackTrace(pw);
pw.flush();
return e.getMessage()+"\n\r"+bout.toString();
}
}
@Override
public List<Map<String,Object>> doMQLSelectObjects(final Modifiable E, final String mql) throws MQLException
{
final Map<String,Object> defined=new TreeMap<String,Object>();
final XMLTag piece=CMLib.xml().createNewTag("tag", "value");
try
{
return doMQLSelectObjs(E,null,null,mql,piece,defined);
}
catch(final PostProcessException e)
{
throw new MQLException("Cannot post-process MQL.", e);
}
}
protected String strFilter(Modifiable E, final List<String> ignoreStats, final String defPrefix, String str, final XMLTag piece, final Map<String,Object> defined) throws CMException,PostProcessException
{
List<Varidentifier> vars=parseVariables(str);
final boolean killArticles=str.toLowerCase().startsWith("(a(n))");
while(vars.size()>0)
{
final Varidentifier V=vars.remove(vars.size()-1);
Object val;
if(V.isMathExpression)
{
final String expression=strFilter(E,ignoreStats,defPrefix,V.var,piece, defined);
if(CMath.isMathExpression(expression))
{
if(expression.indexOf('.')>0)
val=""+CMath.parseMathExpression(expression);
else
val=""+CMath.parseLongExpression(expression);
}
else
throw new CMException("Invalid math expression '$"+expression+"' in str '"+str+"'");
}
else
if(V.var.toUpperCase().startsWith("SELECT:"))
{
val=doMQLSelectString(E,ignoreStats,defPrefix,V.var,piece, defined);
}
else
if(V.var.toUpperCase().startsWith("STAT:") && (E!=null))
{
final String[] parts=V.var.toUpperCase().split(":");
if(E instanceof Environmental)
{
Environmental E2=(Environmental)E;
for(int p=1;p<parts.length-1;p++)
{
final Room R=CMLib.map().roomLocation(E2);
Environmental E3;
if(parts[p].equals("ROOM"))
E3=CMLib.map().roomLocation(E2);
else
if(parts[p].equals("AREA"))
E3=CMLib.map().areaLocation(E2);
else
if(CMLib.directions().getDirectionCode(parts[p])>=0)
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
final int dir=CMLib.directions().getDirectionCode(parts[p]);
E3=R.getRoomInDir(dir);
}
else
if(parts[p].equals("ANYROOM"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
final List<Room> dirs=new ArrayList<Room>();
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
final Room R2=R.getRoomInDir(d);
if((R2!=null)
&&((R2.roomID().length()>0)
||((R.rawDoors()[d] instanceof GridLocale)
&&(R.rawDoors()[d].roomID().length()>0))))
dirs.add(R2);
}
if(dirs.size()==0)
throw new PostProcessException("No anyrooms on object "+E2.ID()+" ("+R.roomID()+"/"+R+") in variable '"+V.var+"' ");
E3=dirs.get(CMLib.dice().roll(1, dirs.size(), -1));
}
else
if(parts[p].equals("MOB"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
if((R.numInhabitants()==0)||((E2 instanceof MOB)&&(R.numInhabitants()==1)))
throw new PostProcessException("No mobs in room for "+E2.ID()+" in variable '"+V.var+"'");
E3=R.fetchInhabitant(CMLib.dice().roll(1, R.numInhabitants(), -1));
}
else
if(parts[p].equals("ITEM"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
if((R.numItems()==0)||((E2 instanceof Item)&&(R.numItems()==1)))
throw new PostProcessException("No items in room for "+E2.ID()+" in variable '"+V.var+"'");
E3=R.getItem(CMLib.dice().roll(1, R.numItems(), -1));
}
else
if(parts[p].equals("AREAGATE"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
final List<Room> dirs=new ArrayList<Room>();
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
final Room R2=R.getRoomInDir(d);
if((R2!=null) && (R2.roomID().length()>0) && (R.getArea()!=R2.getArea()))
dirs.add(R.getRoomInDir(d));
}
if(dirs.size()==0)
{
if(defined.get("ROOMTAG_GATEEXITROOM") instanceof Room)
dirs.add((Room)defined.get("ROOMTAG_GATEEXITROOM"));
if(dirs.size()==0)
throw new PostProcessException("No areagates on object "+E2.ID()+" in variable '"+V.var+"'");
}
E3=dirs.get(CMLib.dice().roll(1, dirs.size(), -1));
}
else
throw new PostProcessException("Unknown stat code '"+parts[p]+"' on object "+E2.ID()+" in variable '"+V.var+"'");
if(E3==null)
throw new PostProcessException("Unknown '"+parts[p]+"' on object "+E2.ID()+" in variable '"+V.var+"'");
else
E2=E3;
}
E=E2;
}
if (E.isStat(parts[parts.length-1]))
val=E.getStat(parts[parts.length-1]);
else
throw new CMException("Unknown stat code '"+parts[parts.length-1]+"' on object "+E+" in variable '"+V.var+"'");
}
else
val = defined.get(V.var.toUpperCase().trim());
if(val instanceof XMLTag)
{
val = findString(E,ignoreStats,defPrefix,"STRING",(XMLTag)val,defined);
}
if((val == null)&&(defPrefix!=null)&&(defPrefix.length()>0)&&(E!=null))
{
String preValue=V.var;
if(preValue.toUpperCase().startsWith(defPrefix.toUpperCase()))
{
preValue=preValue.toUpperCase().substring(defPrefix.length());
if((E.isStat(preValue))
&&((ignoreStats==null)||(!ignoreStats.contains(preValue.toUpperCase()))))
{
val=fillOutStatCode(E,ignoreStats,defPrefix,preValue,piece,defined, false);
XMLTag statPiece=piece;
while((val == null)
&&(statPiece.parent()!=null)
&&(!(defPrefix.startsWith(statPiece.tag())&&(!defPrefix.startsWith(statPiece.parent().tag())))))
{
statPiece=statPiece.parent();
val=fillOutStatCode(E,ignoreStats,defPrefix,preValue,statPiece,defined, false);
}
if((ignoreStats!=null)&&(val!=null))
ignoreStats.add(preValue.toUpperCase());
}
}
}
if(val == null)
throw new CMException("Unknown variable '$"+V.var+"' in str '"+str+"'",new CMException("$"+V.var));
if(V.toUpperCase)
val=val.toString().toUpperCase();
if(V.toLowerCase)
val=val.toString().toLowerCase();
if(V.toPlural)
val=CMLib.english().removeArticleLead(CMLib.english().makePlural(val.toString()));
if(V.toCapitalized)
val=CMStrings.capitalizeAndLower(val.toString());
if(V.toOneWord)
val=CMStrings.removePunctuation(val.toString().replace(' ', '_'));
if(killArticles)
val=CMLib.english().removeArticleLead(val.toString());
str=str.substring(0,V.outerStart)+val.toString()+str.substring(V.outerEnd);
if(vars.size()==0)
vars=parseVariables(str);
}
int x=str.toLowerCase().indexOf("(a(n))");
while((x>=0)&&(x<str.length()-8))
{
if((Character.isWhitespace(str.charAt(x+6)))
&&(Character.isLetter(str.charAt(x+7))))
{
if(CMStrings.isVowel(str.charAt(x+7)))
str=str.substring(0,x)+"an"+str.substring(x+6);
else
str=str.substring(0,x)+"a"+str.substring(x+6);
}
else
str=str.substring(0,x)+"a"+str.substring(x+6);
x=str.toLowerCase().indexOf("(a(n))");
}
return CMLib.xml().restoreAngleBrackets(str).replace('\'','`');
}
@Override
public String findString(final String tagName, final XMLTag piece, final Map<String, Object> defined) throws CMException
{
return findStringNow(null,null,null,tagName,piece,defined);
}
protected String findStringNow(final String tagName, final XMLTag piece, final Map<String, Object> defined) throws CMException
{
return findStringNow(null,null,null,tagName,piece,defined);
}
protected int makeNewLevel(final int level, final int oldMin, final int oldMax, final int newMin, final int newMax)
{
final double oldRange = oldMax-oldMin;
final double myOldRange = level - oldMin;
final double pctOfOldRange = myOldRange/oldRange;
final double newRange = newMax-newMin;
return newMin + (int)Math.round(pctOfOldRange * newRange);
}
@Override
public boolean relevelRoom(final Room room, final int oldMin, final int oldMax, final int newMin, final int newMax)
{
boolean changeMade=false;
try
{
room.toggleMobility(false);
CMLib.threads().suspendResumeRecurse(room, false, true);
if(CMLib.law().getLandTitle(room)!=null)
return false;
for(final Enumeration<Item> i=room.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if(I==null)
continue;
if((I instanceof Weapon)||(I instanceof Armor))
{
int newILevel=makeNewLevel(I.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newILevel <= 0)
newILevel = 1;
if(newILevel != I.phyStats().level())
{
final int levelDiff = newILevel - I.phyStats().level();
changeMade=true;
final int effectiveLevel =CMLib.itemBuilder().timsLevelCalculator(I) + levelDiff;
I.basePhyStats().setLevel(effectiveLevel);
I.phyStats().setLevel(effectiveLevel);
CMLib.itemBuilder().itemFix(I, effectiveLevel, null);
I.basePhyStats().setLevel(newILevel);
I.phyStats().setLevel(newILevel);
I.text();
}
}
}
for(final Enumeration<MOB> m=room.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)
&&(M.isMonster())
&&(M.getStartRoom()==room))
{
int newLevel=makeNewLevel(M.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newLevel <= 0)
newLevel = 1;
if(newLevel != M.phyStats().level())
{
changeMade=true;
final double spdDif = M.basePhyStats().speed() - CMLib.leveler().getLevelMOBSpeed(M);
final int armDif = M.basePhyStats().armor()-CMLib.leveler().getLevelMOBArmor(M);
final int dmgDif = M.basePhyStats().damage()-CMLib.leveler().getLevelMOBDamage(M);
final int attDif = M.basePhyStats().attackAdjustment()-CMLib.leveler().getLevelAttack(M);
M.basePhyStats().setLevel(newLevel);
M.phyStats().setLevel(newLevel);
CMLib.leveler().fillOutMOB(M,M.basePhyStats().level());
M.basePhyStats().setSpeed(M.basePhyStats().speed()+spdDif);
M.basePhyStats().setArmor(M.basePhyStats().armor()+armDif);
M.basePhyStats().setDamage(M.basePhyStats().damage()+dmgDif);
M.basePhyStats().setAttackAdjustment(M.basePhyStats().attackAdjustment()+attDif);
}
for(final Enumeration<Item> mi=M.items();mi.hasMoreElements();)
{
final Item mI=mi.nextElement();
if(mI!=null)
{
int newILevel=makeNewLevel(mI.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newILevel <= 0)
newILevel = 1;
if(newILevel != mI.phyStats().level())
{
final int levelDiff = newILevel - mI.phyStats().level();
changeMade=true;
final int effectiveLevel =CMLib.itemBuilder().timsLevelCalculator(mI) + levelDiff;
mI.basePhyStats().setLevel(effectiveLevel);
mI.phyStats().setLevel(effectiveLevel);
CMLib.itemBuilder().itemFix(mI, effectiveLevel, null);
mI.basePhyStats().setLevel(newILevel);
mI.phyStats().setLevel(newILevel);
mI.text();
}
}
}
final ShopKeeper SK=CMLib.coffeeShops().getShopKeeper(M);
if(SK!=null)
{
for(final Iterator<CoffeeShop.ShelfProduct> i=SK.getShop().getStoreShelves();i.hasNext();)
{
final CoffeeShop.ShelfProduct P=i.next();
final Environmental E2=P.product;
if((E2 instanceof Item)||(E2 instanceof MOB))
{
final Physical P2=(Physical)E2;
newLevel=makeNewLevel(P2.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newLevel <= 0)
newLevel = 1;
if(newLevel != P2.phyStats().level())
{
changeMade=true;
if(E2 instanceof Item)
{
final Item I2=(Item)E2;
final int levelDiff = newLevel - I2.phyStats().level();
final int effectiveLevel =CMLib.itemBuilder().timsLevelCalculator(I2) + levelDiff;
I2.basePhyStats().setLevel(effectiveLevel);
I2.phyStats().setLevel(effectiveLevel);
CMLib.itemBuilder().itemFix(I2, effectiveLevel, null);
}
P2.basePhyStats().setLevel(newLevel);
P2.phyStats().setLevel(newLevel);
if(E2 instanceof MOB)
CMLib.leveler().fillOutMOB((MOB)E2,P2.basePhyStats().level());
E2.text();
}
}
}
}
M.text();
M.recoverCharStats();
M.recoverMaxState();
M.recoverPhyStats();
M.recoverCharStats();
M.recoverMaxState();
M.recoverPhyStats();
M.resetToMaxState();
}
}
}
catch(final Exception e)
{
Log.errOut(e);
changeMade=false;
}
finally
{
room.recoverRoomStats();
CMLib.threads().suspendResumeRecurse(room, false, false);
room.toggleMobility(true);
room.recoverRoomStats();
}
return changeMade;
}
}
|
com/planet_ink/coffee_mud/Libraries/MUDPercolator.java
|
package com.planet_ink.coffee_mud.Libraries;
import com.planet_ink.coffee_mud.core.exceptions.CMException;
import com.planet_ink.coffee_mud.core.exceptions.MQLException;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.Area.State;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.AreaGenerationLibrary.LayoutNode;
import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary.XMLTag;
import com.planet_ink.coffee_mud.Libraries.interfaces.AbilityMapper.AbilityMapping;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.io.*;
/*
Copyright 2008-2019 Bo Zimmerman
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.
*/
public class MUDPercolator extends StdLibrary implements AreaGenerationLibrary
{
@Override
public String ID()
{
return "MUDPercolator";
}
protected final static char[] splitters=new char[]{'<','>','='};
protected final static Triad<Integer,Integer,Class<?>[]> emptyMetacraftFilter = new Triad<Integer,Integer,Class<?>[]>(Integer.valueOf(-1),Integer.valueOf(-1),new Class<?>[0]);
protected final static String POST_PROCESSING_STAT_SETS="___POST_PROCESSING_SETS___";
protected final static Set<String> UPPER_REQUIRES_KEYWORDS=new XHashSet<String>(new String[]{"INT","INTEGER","$","STRING","ANY","DOUBLE","#","NUMBER"});
protected final static CMParms.DelimiterChecker REQUIRES_DELIMITERS=CMParms.createDelimiter(new char[]{' ','\t',',','\r','\n'});
private final SHashtable<String,Class<LayoutManager>> mgrs = new SHashtable<String,Class<LayoutManager>>();
private interface BuildCallback
{
public void willBuild(Environmental E, XMLTag XMLTag);
}
private static final Filterer<MOB> noMobFilter = new Filterer<MOB>()
{
@Override
public boolean passesFilter(final MOB obj)
{
return (obj != null) && (CMLib.flags().isInTheGame(obj, true));
}
};
private static final Filterer<MOB> npcFilter = new Filterer<MOB>()
{
@Override
public boolean passesFilter(final MOB obj)
{
return (obj != null)
&& (!obj.isPlayer())
&&((obj.amFollowing()==null)||(!obj.amUltimatelyFollowing().isPlayer()));
}
};
private static final Converter<Session, MOB> sessionToMobConvereter= new Converter<Session, MOB>()
{
@Override
public MOB convert(final Session obj)
{
// TODO Auto-generated method stub
return null;
}
};
private static final Comparator<Object> objComparator = new Comparator<Object>()
{
@Override
public int compare(final Object o1, final Object o2)
{
final String s1=(o1 instanceof Environmental)?((Environmental)o1).Name():(o1==null?"":o1.toString());
final String s2=(o1 instanceof Environmental)?((Environmental)o2).Name():(o2==null?"":o2.toString());
if(CMath.isNumber(s1) && CMath.isNumber(s2))
{
final double d1=CMath.s_double(s1);
final double d2=CMath.s_double(s2);
return (d1==d2)?0:(d1>d2?1:-1);
}
return s1.compareToIgnoreCase(s2);
}
};
@Override
public LayoutManager getLayoutManager(final String named)
{
final Class<LayoutManager> mgr = mgrs.get(named.toUpperCase().trim());
if(mgr != null)
{
try
{
return mgr.newInstance();
}
catch(final Exception e)
{
return null;
}
}
return null;
}
@Override
public void buildDefinedIDSet(final List<XMLTag> xmlRoot, final Map<String,Object> defined)
{
if(xmlRoot==null)
return;
for(int v=0;v<xmlRoot.size();v++)
{
final XMLLibrary.XMLTag piece = xmlRoot.get(v);
final String id = piece.getParmValue("ID");
if((id!=null)&&(id.length()>0))
{
final Object o=defined.get(id.toUpperCase());
if(o != null)
{
if(!(o instanceof XMLTag))
Log.errOut("Duplicate ID: "+id+" (first tag did not resolve to a complex piece -- it wins.)");
else
{
final Boolean pMergeVal;
if((piece.parms()==null)||(!piece.parms().containsKey("MERGE")))
pMergeVal = null;
else
pMergeVal = Boolean.valueOf(CMath.s_bool(piece.parms().get("MERGE")));
final Boolean oMergeVal;
if((((XMLTag)o).parms()==null)||(!((XMLTag)o).parms().containsKey("MERGE")))
oMergeVal = null;
else
oMergeVal = Boolean.valueOf(CMath.s_bool(((XMLTag)o).parms().get("MERGE")));
if((pMergeVal == null)||(oMergeVal == null))
Log.errOut("Duplicate ID: "+id+" (no MERGE tag found to permit this operation -- first tag wins.)");
else
if(pMergeVal.booleanValue() && oMergeVal.booleanValue())
{
final XMLTag src=piece;
final XMLTag tgt=(XMLTag)o;
if(!src.tag().equalsIgnoreCase(tgt.tag()))
Log.errOut("Unable to merge tags with ID: "+id+", they are of different types.");
else
for(final String parm : src.parms().keySet())
{
final String srcParmVal=src.parms().get(parm);
final String tgtParmVal=tgt.parms().get(parm);
if(tgtParmVal==null)
tgt.parms().put(parm,srcParmVal);
else
if(tgtParmVal.equalsIgnoreCase(srcParmVal)||parm.equalsIgnoreCase("ID"))
{
/* do nothing -- nothing to do */
}
else
if(parm.equalsIgnoreCase("REQUIRES"))
{
final Map<String,String> srcParms=CMParms.parseEQParms(srcParmVal, REQUIRES_DELIMITERS, true);
final Map<String,String> tgtParms=CMParms.parseEQParms(tgtParmVal, REQUIRES_DELIMITERS, true);
for(final String srcKey : srcParms.keySet())
{
final String srcVal=srcParms.get(srcKey);
final String tgtVal=tgtParms.get(srcKey);
if(tgtVal == null)
tgtParms.put(srcKey, srcVal);
else
if(UPPER_REQUIRES_KEYWORDS.contains(srcVal.toUpperCase()))
{
if(!srcVal.equalsIgnoreCase(tgtVal))
Log.errOut("Unable to merge REQUIRES parm on tags with ID: "+id+", mismatch in requirements for '"+srcKey+"'.");
}
else
if(UPPER_REQUIRES_KEYWORDS.contains(tgtVal.toUpperCase()))
Log.errOut("Unable to merge REQUIRES parm on tags with ID: "+id+", mismatch in requirements for '"+srcKey+"'.");
else
tgtParms.put(srcKey,srcVal+";"+tgtVal);
}
tgt.parms().put(parm, CMParms.combineEQParms(tgtParms, ','));
}
else
if(parm.equalsIgnoreCase("CONDITION")||parm.equalsIgnoreCase("VALIDATE"))
tgt.parms().put(parm, tgtParmVal+" and "+srcParmVal);
else
if(parm.equalsIgnoreCase("INSERT")||parm.equalsIgnoreCase("DEFINE")||parm.equalsIgnoreCase("PREDEFINE"))
tgt.parms().put(parm, tgtParmVal+","+srcParmVal);
else
Log.errOut("Unable to merge SELECT parm on tags with ID: "+id+".");
}
for(final XMLLibrary.XMLTag subPiece : src.contents())
{
final Boolean subMergeVal;
if((subPiece.parms()==null)||(!subPiece.parms().containsKey("MERGE")))
subMergeVal = null;
else
subMergeVal = Boolean.valueOf(CMath.s_bool(subPiece.parms().get("MERGE")));
if((subMergeVal == null)||(subMergeVal.booleanValue()))
tgt.contents().add(subPiece);
}
}
}
}
else
defined.put(id.toUpperCase().trim(),piece);
}
final String load = piece.getParmValue("LOAD");
if((load!=null)&&(load.length()>0))
{
piece.parms().remove("LOAD");
XMLTag loadedPiece=(XMLTag)defined.get("SYSTEM_LOADED_XML_FILES");
if(loadedPiece==null)
{
loadedPiece=CMLib.xml().createNewTag("SYSTEM_LOADED_XML_FILES","");
defined.put("SYSTEM_LOADED_XML_FILES", loadedPiece);
}
final CMFile file = new CMFile(load,null,CMFile.FLAG_LOGERRORS|CMFile.FLAG_FORCEALLOW);
if(loadedPiece.getPieceFromPieces( file.getAbsolutePath().toUpperCase())==null)
{
loadedPiece.contents().add(CMLib.xml().createNewTag(file.getAbsolutePath().toUpperCase(),"true"));
if(file.exists() && file.canRead())
{
final List<XMLTag> addPieces=CMLib.xml().parseAllXML(file.text());
piece.contents().addAll(addPieces);
}
}
}
buildDefinedIDSet(piece.contents(),defined);
}
}
//@Override public
void testMQLParsing()
{
final String[] testMQLs = new String[] {
"SELECT: x from y where xxx > ydd and ( yyy<=djj ) or zzz > jkkk",
"SELECT: x from y where xxx > ydd and ttt>3 or ( yyy<=djj ) and zzz > jkkk or 6>7",
"SELECT: x from y",
"SELECT: x, XX from y",
"SELECT: x,xx,xxx from y",
"SELECT: x, xx , xxx from y",
"SELECT: x, xx , xxx from (select: x from y)",
"SELECT: x from y where x>y",
"SELECT: x from y where x >y",
"SELECT: x from y where x> y",
"SELECT: x from y where xxx> ydd and yyy<=djj",
"SELECT: x from y where xxx> ydd and yyy<=djj or zzz > jkkk and rrr>ddd",
"SELECT: x from (select: x from y) where (xxx > ydd) and ( yyy<=djj ) or (zzz > jkkk)and(rrr>ddd)",
"SELECT: x from y where ((xxx > ydd) and ( yyy<=djj )) or((zzz > jkkk)and ((rrr>ddd) or (ddd>888)))",
};
for(int i=0;i<testMQLs.length;i++)
{
final String mqlWSelect=testMQLs[i];
final int x=mqlWSelect.indexOf(':');
final String mql=mqlWSelect.substring(x+1).toUpperCase().trim();
try
{
final MQLClause clause = new MQLClause();
clause.parseMQL(testMQLs[i], mql);
}
catch(final Exception e)
{
System.out.println(e.getMessage());
}
}
}
@Override
@SuppressWarnings("unchecked")
public boolean activate()
{
final String filePath="com/planet_ink/coffee_mud/Libraries/layouts";
final CMProps page = CMProps.instance();
final Vector<Object> layouts=CMClass.loadClassList(filePath,page.getStr("LIBRARY"),"/layouts",LayoutManager.class,true);
for(int f=0;f<layouts.size();f++)
{
final LayoutManager lmgr= (LayoutManager)layouts.elementAt(f);
final Class<LayoutManager> lmgrClass=(Class<LayoutManager>)lmgr.getClass();
mgrs.put(lmgr.name().toUpperCase().trim(),lmgrClass);
}
return true;
}
@Override
public boolean shutdown()
{
mgrs.clear();
return true;
}
private final static class PostProcessException extends Exception
{
private static final long serialVersionUID = -8797769166795010761L;
public PostProcessException(final String s)
{
super(s);
}
}
protected abstract class PostProcessAttempt
{
protected Map<String,Object> defined=null;
protected boolean firstRun=true;
public abstract String attempt() throws CMException,PostProcessException;
}
@SuppressWarnings("unchecked")
protected final String PostProcessAttempter(final Map<String,Object> defined, final PostProcessAttempt attempter) throws CMException
{
try
{
attempter.defined=defined;
final String result = attempter.attempt();
return result;
}
catch(final PostProcessException pe)
{
List<PostProcessAttempt> posties=(List<PostProcessAttempt>)defined.get(MUDPercolator.POST_PROCESSING_STAT_SETS);
if(posties==null)
{
posties=new Vector<PostProcessAttempt>();
defined.put(MUDPercolator.POST_PROCESSING_STAT_SETS, posties);
}
attempter.firstRun=false;
final Map<String,Object> definedCopy;
if(defined instanceof Hashtable)
definedCopy=(Map<String,Object>)((Hashtable<String,Object>)defined).clone();
else
definedCopy=new Hashtable<String,Object>(defined);
attempter.defined=definedCopy;
posties.add(attempter);
return null;
}
}
protected void fillOutRequiredStatCodeSafe(final Modifiable E, final List<String> ignoreStats, final String defPrefix,
final String tagName, final String statName, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String val = findString(E,ignoreStats,defPrefix,tagName,piece,this.defined);
E.setStat(statName, val);
if((defPrefix!=null)&&(defPrefix.length()>0))
addDefinition(defPrefix+tagName,val,defined);
return val;
}
});
}
// vars created: ROOM_CLASS, ROOM_TITLE, ROOM_DESCRIPTION, ROOM_CLASSES, ROOM_TITLES, ROOM_DESCRIPTIONS
@Override
public Room buildRoom(final XMLTag piece, final Map<String,Object> defined, final Exit[] exits, final int direction) throws CMException
{
addDefinition("DIRECTION",CMLib.directions().getDirectionName(direction).toLowerCase(),defined);
final String classID = findStringNow("class",piece,defined);
final Room R = CMClass.getLocale(classID);
if(R == null)
throw new CMException("Unable to build room on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
addDefinition("ROOM_CLASS",classID,defined);
final List<String> ignoreStats=new XArrayList<String>(new String[]{"CLASS","DISPLAY","DESCRIPTION"});
fillOutRequiredStatCodeSafe(R, ignoreStats, "ROOM_", "TITLE", "DISPLAY", piece, defined);
fillOutRequiredStatCodeSafe(R, ignoreStats, "ROOM_", "DESCRIPTION", "DESCRIPTION", piece, defined);
fillOutCopyCodes(R, ignoreStats, "ROOM_", piece, defined);
fillOutStatCodes(R, ignoreStats, "ROOM_", piece, defined);
final List<MOB> mV = findMobs(piece,defined);
for(int i=0;i<mV.size();i++)
{
final MOB M=mV.get(i);
M.setSavable(true);
M.bringToLife(R,true);
}
final List<Item> iV = findItems(piece,defined);
for(int i=0;i<iV.size();i++)
{
final Item I=iV.get(i);
R.addItem(I);
I.setSavable(true);
I.setExpirationDate(0);
}
final List<Ability> aV = findAffects(R,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability A=aV.get(i);
A.setSavable(true);
R.addNonUninvokableEffect(A);
}
final List<Behavior> bV = findBehaviors(R,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
R.addBehavior(B);
}
for(int dir=0;dir<Directions.NUM_DIRECTIONS();dir++)
{
Exit E=exits[dir];
if((E==null)&&(defined.containsKey("ROOMLINK_"+CMLib.directions().getDirectionChar(dir).toUpperCase())))
{
defined.put("ROOMLINK_DIR",CMLib.directions().getDirectionChar(dir).toUpperCase());
final Exit E2=findExit(R,piece, defined);
if(E2!=null)
E=E2;
defined.remove("ROOMLINK_DIR");
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","EXIT:NEW:"+((E==null)?"null":E.ID())+":DIR="+CMLib.directions().getDirectionChar(dir).toUpperCase()+":ROOM="+R.getStat("DISPLAY"));
}
else
if((CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))&&defined.containsKey("ROOMLINK_"+CMLib.directions().getDirectionChar(dir).toUpperCase()))
Log.debugOut("MUDPercolator","EXIT:OLD:"+((E==null)?"null":E.ID())+":DIR="+CMLib.directions().getDirectionChar(dir).toUpperCase()+":ROOM="+R.getStat("DISPLAY"));
R.setRawExit(dir, E);
R.startItemRejuv();
}
return R;
}
@SuppressWarnings("unchecked")
@Override
public void postProcess(final Map<String,Object> defined) throws CMException
{
final List<PostProcessAttempt> posties=(List<PostProcessAttempt>)defined.get(MUDPercolator.POST_PROCESSING_STAT_SETS);
if(posties == null)
return;
try
{
for(final PostProcessAttempt stat : posties)
{
try
{
stat.attempt();
}
catch(final PostProcessException pe)
{
throw pe;
}
}
}
catch(final PostProcessException pe)
{
throw new CMException("Unsatisfied Post Process Exception: "+pe.getMessage(),pe);
}
}
protected void layoutRecursiveFill(final LayoutNode n, final HashSet<LayoutNode> nodesDone, final Vector<LayoutNode> group, final LayoutTypes type)
{
if(n != null)
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
if(n.links().containsKey(Integer.valueOf(d)))
{
final LayoutNode offN=n.links().get(Integer.valueOf(d));
if((offN.type()==type)
&&(!group.contains(offN))
&&(!nodesDone.contains(offN)))
{
group.addElement(offN);
nodesDone.add(offN);
layoutRecursiveFill(offN,nodesDone,group,type);
}
}
}
}
protected void layoutFollow(LayoutNode n, final LayoutTypes type, final int direction, final HashSet<LayoutNode> nodesAlreadyGrouped, final List<LayoutNode> group)
{
n=n.links().get(Integer.valueOf(direction));
while((n != null) &&(n.type()==LayoutTypes.street) &&(!group.contains(n) &&(!nodesAlreadyGrouped.contains(n))))
{
nodesAlreadyGrouped.add(n);
group.add(n);
n=n.links().get(Integer.valueOf(direction));
}
}
@Override
public Area findArea(final XMLTag piece, final Map<String,Object> defined, final int directions) throws CMException
{
try
{
final String tagName="AREA";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
{
return null;
}
while(choices.size()>0)
{
final XMLLibrary.XMLTag valPiece = choices.get(CMLib.dice().roll(1,choices.size(),-1));
choices.remove(valPiece);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(null,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final Map<String,Object> rDefined=new Hashtable<String,Object>();
rDefined.putAll(defined);
defineReward(null,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,rDefined,true);
final Area A=buildArea(valPiece,rDefined,directions);
for (final String key : rDefined.keySet())
{
if(key.startsWith("_"))
defined.put(key,rDefined.get(key));
}
return A;
}
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
return null;
}
protected Area buildArea(final XMLTag piece, final Map<String,Object> defined, final int direction) throws CMException
{
defined.put("DIRECTION",CMLib.directions().getDirectionName(direction).toLowerCase());
final String classID = findStringNow("class",piece,defined);
final Area A = CMClass.getAreaType(classID);
if(A == null)
throw new CMException("Unable to build area on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
defined.put("AREA_CLASS",classID);
final String name = findStringNow(A,null,"AREA_","NAME",piece,defined);
if(CMLib.map().getArea(name)!=null)
{
A.destroy();
throw new CMException("Unable to create area '"+name+"', you must destroy the old one first.");
}
A.setName(name);
defined.put("AREA_NAME",name);
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String author = findOptionalString(A,null,"AREA_","author",piece,this.defined, false);
if(author != null)
{
A.setAuthorID(author);
defined.put("AREA_AUTHOR",author);
}
return author;
}
});
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String description = findOptionalString(A,null,"AREA_","description",piece,this.defined, false);
if(description != null)
{
A.setDescription(description);
defined.put("AREA_DESCRIPTION",description);
}
return description;
}
});
if(fillInArea(piece, defined, A, direction))
return A;
throw new CMException("Unable to build area for some reason.");
}
protected void updateLayoutDefinitions(final Map<String,Object> defined, final Map<String,Object> groupDefined,
final Map<List<LayoutNode>,Map<String,Object>> groupDefinitions, final List<List<LayoutNode>> roomGroups)
{
for (final String key : groupDefined.keySet())
{
if(key.startsWith("__"))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("AREADEF:"+key+"="+CMStrings.limit(groupDefined.get(key).toString(), 10));
defined.put(key, groupDefined.get(key));
for(final List<LayoutNode> group2 : roomGroups)
{
final Map<String,Object> groupDefined2 = groupDefinitions.get(group2);
if(groupDefined2!=groupDefined)
groupDefined2.put(key, groupDefined.get(key));
}
}
}
}
@SuppressWarnings("unchecked")
protected Room layOutRooms(final Area A, final LayoutManager layoutManager, final int size, final int direction, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","Using LayoutManager:"+layoutManager.name());
final Random random=new Random(System.currentTimeMillis());
final List<LayoutNode> roomsToLayOut = layoutManager.generate(size,direction);
if((roomsToLayOut==null)||(roomsToLayOut.size()==0))
throw new CMException("Unable to fill area of size "+size+" off layout "+layoutManager.name());
int numLeafs=0;
for(int i=0;i<roomsToLayOut.size();i++)
{
final LayoutNode node=roomsToLayOut.get(i);
if(node.type()==LayoutTypes.leaf)
numLeafs++;
if(node.links().size()==0)
throw new CMException("Created linkless node with "+layoutManager.name());
}
defined.put("AREA_NUMLEAFS", ""+numLeafs);
// now break our rooms into logical groups, generate those rooms.
final List<List<LayoutNode>> roomGroups = new Vector<List<LayoutNode>>();
final LayoutNode magicRoomNode = roomsToLayOut.get(0);
final HashSet<LayoutNode> nodesAlreadyGrouped=new HashSet<LayoutNode>();
boolean keepLooking=true;
while(keepLooking)
{
keepLooking=false;
for(int i=0;i<roomsToLayOut.size();i++)
{
final LayoutNode node=roomsToLayOut.get(i);
if(node.type()==LayoutTypes.leaf)
{
final Vector<LayoutNode> group=new Vector<LayoutNode>();
group.add(node);
nodesAlreadyGrouped.add(node);
for(final Integer linkDir : node.links().keySet())
{
final LayoutNode dirNode=node.links().get(linkDir);
if(!nodesAlreadyGrouped.contains(dirNode))
{
if((dirNode.type()==LayoutTypes.leaf)
||(dirNode.type()==LayoutTypes.interior)&&(node.isFlagged(LayoutFlags.offleaf)))
{
group.addElement(dirNode);
nodesAlreadyGrouped.add(dirNode);
}
}
}
for(final LayoutNode n : group)
roomsToLayOut.remove(n);
if(group.size()>0)
{
// randomize the leafs a bit
if(roomGroups.size()==0)
roomGroups.add(group);
else
roomGroups.add(random.nextInt(roomGroups.size()),group);
}
keepLooking=true;
break;
}
}
}
keepLooking=true;
while(keepLooking)
{
keepLooking=false;
for(int i=0;i<roomsToLayOut.size();i++)
{
final LayoutNode node=roomsToLayOut.get(i);
if(node.type()==LayoutTypes.street)
{
final List<LayoutNode> group=new Vector<LayoutNode>();
group.add(node);
nodesAlreadyGrouped.add(node);
final LayoutRuns run=node.getFlagRuns();
if(run==LayoutRuns.ns)
{
layoutFollow(node,LayoutTypes.street,Directions.NORTH,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.SOUTH,nodesAlreadyGrouped,group);
}
else
if(run==LayoutRuns.ew)
{
layoutFollow(node,LayoutTypes.street,Directions.EAST,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.WEST,nodesAlreadyGrouped,group);
}
else
if(run==LayoutRuns.nesw)
{
layoutFollow(node,LayoutTypes.street,Directions.NORTHEAST,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.SOUTHWEST,nodesAlreadyGrouped,group);
}
else
if(run==LayoutRuns.nwse)
{
layoutFollow(node,LayoutTypes.street,Directions.NORTHWEST,nodesAlreadyGrouped,group);
layoutFollow(node,LayoutTypes.street,Directions.SOUTHEAST,nodesAlreadyGrouped,group);
}
else
{
int topDir=-1;
int topSize=-1;
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
if(node.links().get(Integer.valueOf(d))!=null)
{
final List<LayoutNode> grpCopy=new XArrayList<LayoutNode>(group);
final HashSet<LayoutNode> nodesAlreadyGroupedCopy=(HashSet<LayoutNode>)nodesAlreadyGrouped.clone();
layoutFollow(node,LayoutTypes.street,d,nodesAlreadyGroupedCopy,grpCopy);
if(node.links().get(Integer.valueOf(Directions.getOpDirectionCode(d)))!=null)
layoutFollow(node,LayoutTypes.street,Directions.getOpDirectionCode(d),nodesAlreadyGroupedCopy,grpCopy);
if(grpCopy.size()>topSize)
{
topSize=grpCopy.size();
topDir=d;
}
}
}
if(topDir>=0)
{
layoutFollow(node,LayoutTypes.street,topDir,nodesAlreadyGrouped,group);
if(node.links().get(Integer.valueOf(Directions.getOpDirectionCode(topDir)))!=null)
layoutFollow(node,LayoutTypes.street,Directions.getOpDirectionCode(topDir),nodesAlreadyGrouped,group);
}
}
for(final LayoutNode n : group)
roomsToLayOut.remove(n);
if(group.size()>0)
roomGroups.add(group);
keepLooking=true;
}
}
}
while(roomsToLayOut.size() >0)
{
final LayoutNode node=roomsToLayOut.get(0);
final Vector<LayoutNode> group=new Vector<LayoutNode>();
group.add(node);
nodesAlreadyGrouped.add(node);
layoutRecursiveFill(node,nodesAlreadyGrouped,group,node.type());
for(final LayoutNode n : group)
roomsToLayOut.remove(n);
roomGroups.add(group);
}
// make CERTAIN that the magic first room in the layout always
// gets ID#0.
List<LayoutNode> magicGroup=null;
for(int g=0;g<roomGroups.size();g++)
{
final List<LayoutNode> group=roomGroups.get(g);
if(group.contains(magicRoomNode))
{
magicGroup=group;
break;
}
}
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
for(int g=0;g<roomGroups.size();g++)
{
final Vector<LayoutNode> group=(Vector<LayoutNode>)roomGroups.get(g);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","GROUP:"+A.Name()+": "+group.firstElement().type().toString()+": "+group.size());
}
final Map<List<LayoutNode>,Map<String,Object>> groupDefinitions=new Hashtable<List<LayoutNode>,Map<String,Object>>();
for(final List<LayoutNode> group : roomGroups)
{
final Map<String,Object> newDefined=new Hashtable<String,Object>();
newDefined.putAll(defined);
groupDefinitions.put(group, newDefined);
}
Map<String,Object> groupDefined = groupDefinitions.get(magicGroup);
final Room magicRoom = processRoom(A,direction,piece,magicRoomNode,groupDefined);
for(final Map<String,Object> otherDefineds : groupDefinitions.values())
{
otherDefineds.remove("ROOMTAG_NODEGATEEXIT");
otherDefineds.remove("ROOMTAG_GATEEXITROOM");
}
updateLayoutDefinitions(defined,groupDefined,groupDefinitions,roomGroups);
//now generate the rooms and add them to the area
for(final List<LayoutNode> group : roomGroups)
{
groupDefined = groupDefinitions.get(group);
for(final LayoutNode node : group)
{
if(node!=magicRoomNode)
processRoom(A,direction,piece,node,groupDefined);
}
updateLayoutDefinitions(defined,groupDefined,groupDefinitions,roomGroups);
}
for(final Integer linkDir : magicRoomNode.links().keySet())
{
if(linkDir.intValue() == Directions.getOpDirectionCode(direction))
Log.errOut("MUDPercolator","Generated an override exit for "+magicRoom.roomID()+", direction="+direction+", layout="+layoutManager.name());
else
{
final LayoutNode linkNode=magicRoomNode.getLink(linkDir.intValue());
if((magicRoom.getRawExit(linkDir.intValue())==null) || (linkNode.room() == null))
Log.errOut("MUDPercolator","Generated an unpaired node for "+magicRoom.roomID());
else
magicRoom.rawDoors()[linkDir.intValue()]=linkNode.room();
}
}
//now do a final-link on the rooms
for(final List<LayoutNode> group : roomGroups)
{
for(final LayoutNode node : group)
{
final Room R=node.room();
if(node != magicRoomNode)
{
if((R==null)||(node.links().keySet().size()==0))
Log.errOut("MUDPercolator",layoutManager.name()+" generated a linkless node: "+node.toString());
else
for(final Integer linkDir : node.links().keySet())
{
final LayoutNode linkNode=node.getLink(linkDir.intValue());
if((R.getRawExit(linkDir.intValue())==null) || (linkNode.room() == null))
Log.errOut("MUDPercolator","Generated an unpaired node for "+R.roomID());
else
R.rawDoors()[linkDir.intValue()]=linkNode.room();
}
}
}
}
return magicRoom;
}
// vars created: LINK_DIRECTION, AREA_CLASS, AREA_NAME, AREA_DESCRIPTION, AREA_LAYOUT, AREA_SIZE
@Override
public boolean fillInArea(final XMLTag piece, final Map<String,Object> defined, final Area A, final int direction) throws CMException
{
final String layoutType = findStringNow("layout",piece,defined);
if((layoutType==null)||(layoutType.trim().length()==0))
throw new CMException("Unable to build area without defined layout");
final LayoutManager layoutManager = getLayoutManager(layoutType);
if(layoutManager == null)
throw new CMException("Undefined Layout "+layoutType);
defined.put("AREA_LAYOUT",layoutManager.name());
String size = findStringNow("size",piece,defined);
if(CMath.isMathExpression(size))
size=Integer.toString(CMath.parseIntExpression(size));
if((!CMath.isInteger(size))||(CMath.s_int(size)<=0))
throw new CMException("Unable to build area of size "+size);
defined.put("AREA_SIZE",size);
final List<String> ignoreStats=new XArrayList<String>(new String[]{"CLASS","NAME","DESCRIPTION","LAYOUT","SIZE"});
fillOutStatCodes(A, ignoreStats,"AREA_",piece,defined);
final List<Ability> aV = findAffects(A,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability AB=aV.get(i);
A.setSavable(true);
A.addNonUninvokableEffect(AB);
}
final List<Behavior> bV = findBehaviors(A,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
A.addBehavior(B);
}
CMLib.map().addArea(A); // necessary for proper naming.
try
{
layOutRooms(A, layoutManager, CMath.s_int(size), direction, piece, defined);
CMLib.map().delArea(A); // we added it for id assignment, now we are done.
}
catch(final Exception t)
{
CMLib.map().delArea(A);
CMLib.map().emptyAreaAndDestroyRooms(A);
A.destroy();
if(t instanceof CMException)
throw (CMException)t;
throw new CMException(t.getMessage(),t);
}
return true;
}
protected Room processRoom(final Area A, final int direction, final XMLTag piece, final LayoutNode node, final Map<String,Object> groupDefined)
throws CMException
{
for(final LayoutTags key : node.tags().keySet())
groupDefined.put("ROOMTAG_"+key.toString().toUpperCase(),node.tags().get(key));
final Exit[] exits=new Exit[Directions.NUM_DIRECTIONS()];
for(final Integer linkDir : node.links().keySet())
{
final LayoutNode linkNode = node.links().get(linkDir);
if(linkNode.room() != null)
{
final int opDir=Directions.getOpDirectionCode(linkDir.intValue());
exits[linkDir.intValue()]=linkNode.room().getExitInDir(opDir);
groupDefined.put("ROOMTITLE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),linkNode.room().displayText(null));
}
groupDefined.put("NODETYPE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),linkNode.type().name());
//else groupDefined.put("ROOMTITLE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),"");
groupDefined.put("ROOMLINK_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase(),"true");
}
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator",A.Name()+": type: "+node.type().toString());
final StringBuffer defs=new StringBuffer("");
for (final String key : groupDefined.keySet())
{
defs.append(key+"="+CMStrings.limit(groupDefined.get(key).toString(),10)+",");
}
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","DEFS: "+defs.toString());
}
final Room R=findRoom(A,piece, groupDefined, exits, direction);
if(R==null)
throw new CMException("Failure to generate room from "+piece.value());
R.setRoomID(A.getNewRoomID(null,-1));
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","ROOMID: "+R.roomID());
R.setArea(A);
A.addProperRoom(R);
node.setRoom(R);
groupDefined.remove("ROOMTAG_NODEGATEEXIT");
groupDefined.remove("ROOMTAG_GATEEXITROOM");
for(final LayoutTags key : node.tags().keySet())
groupDefined.remove("ROOMTAG_"+key.toString().toUpperCase());
for(final Integer linkDir : node.links().keySet())
{
groupDefined.remove("NODETYPE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase());
groupDefined.remove("ROOMLINK_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase());
groupDefined.remove("ROOMTITLE_"+CMLib.directions().getDirectionChar(linkDir.intValue()).toUpperCase());
}
return R;
}
@Override
public List<MOB> findMobs(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
return findMobs(null,piece, defined, null);
}
protected List<MOB> findMobs(final Modifiable E,final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<MOB> V = new Vector<MOB>();
final String tagName="MOB";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Mob: "+CMStrings.limit(valPiece.value(),80)+"...");
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final MOB M=buildMob(valPiece,defined);
if(callBack != null)
callBack.willBuild(M, valPiece);
V.add(M);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Room findRoom(final Area A, final XMLTag piece, final Map<String,Object> defined, final Exit[] exits, final int directions) throws CMException
{
try
{
final String tagName="ROOM";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
{
return null;
}
while(choices.size()>0)
{
final XMLLibrary.XMLTag valPiece = choices.get(CMLib.dice().roll(1,choices.size(),-1));
choices.remove(valPiece);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(null,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final Map<String,Object> rDefined=new Hashtable<String,Object>();
rDefined.putAll(defined);
defineReward(null,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,rDefined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Room: "+CMStrings.limit(valPiece.value(),80)+"...");
Room R;
final String layoutType=valPiece.parms().get("LAYOUT");
if((layoutType!=null)&&(layoutType.length()>0))
{
final LayoutManager layoutManager = getLayoutManager(layoutType);
if(layoutManager == null)
throw new CMException("Undefined room Layout "+layoutType);
rDefined.put("ROOM_LAYOUT",layoutManager.name());
final String size = findStringNow("size",valPiece,rDefined);
if((!CMath.isInteger(size))||(CMath.s_int(size)<=0))
throw new CMException("Unable to build room layout of size "+size);
defined.put("ROOM_SIZE",size);
R=layOutRooms(A, layoutManager, CMath.s_int(size), directions, valPiece, rDefined);
}
else
{
final Exit[] rExits=exits.clone();
R=buildRoom(valPiece,rDefined,rExits,directions);
for(int e=0;e<rExits.length;e++)
exits[e]=rExits[e];
}
for (final String key : rDefined.keySet())
{
if(key.startsWith("_"))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("RGDEF:"+key+"="+CMStrings.limit(rDefined.get(key).toString(), 10));
defined.put(key,rDefined.get(key));
}
}
return R;
}
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
return null;
}
protected PairVector<Room,Exit[]> findRooms(final XMLTag piece, final Map<String,Object> defined, final Exit[] exits, final int direction) throws CMException
{
try
{
final PairVector<Room,Exit[]> DV = new PairVector<Room,Exit[]>();
final String tagName="ROOM";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return DV;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(null,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(null,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Exit[] theseExits=exits.clone();
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Room: "+CMStrings.limit(valPiece.value(),80)+"...");
final Room R=buildRoom(valPiece,defined,theseExits,direction);
DV.addElement(R,theseExits);
}
return DV;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Exit findExit(final Modifiable M, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final String tagName="EXIT";
final List<XMLLibrary.XMLTag> choices = getAllChoices(M,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return null;
final List<Exit> exitChoices = new Vector<Exit>();
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(M,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(M,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Exit: "+CMStrings.limit(valPiece.value(),80)+"...");
final Exit E=buildExit(valPiece,defined);
if(E!=null)
exitChoices.add(E);
}
if(exitChoices.size()==0)
return null;
return exitChoices.get(CMLib.dice().roll(1,exitChoices.size(),-1));
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
private static class Varidentifier
{
public int outerStart=-1;
public int outerEnd=-1;
public String var=null;
public boolean toLowerCase=false;
public boolean toUpperCase=false;
public boolean toCapitalized=false;
public boolean toPlural=false;
public boolean isMathExpression=false;
public boolean toOneWord=false;
}
protected List<Varidentifier> parseVariables(final String str)
{
int x=str.indexOf('$');
final List<Varidentifier> list=new XVector<Varidentifier>();
while((x>=0)&&(x<str.length()-1))
{
final Varidentifier var = new Varidentifier();
var.outerStart=x;
x++;
if((x<str.length())&&(str.charAt(x)=='{'))
{
int varstart=var.outerStart;
x++;
while((x<str.length()-2)&&(str.charAt(x+1)==':'))
{
switch(str.charAt(x))
{
case 'l': case 'L':
var.toLowerCase=true;
break;
case 'u': case 'U':
var.toUpperCase=true;
break;
case 'p': case 'P':
var.toPlural=true;
break;
case 'c': case 'C':
var.toCapitalized=true;
break;
case '_':
var.toOneWord=true;
break;
}
x+=2;
varstart+=2;
}
int depth=0;
while((x<str.length())
&&((str.charAt(x)!='}')||(depth>0)))
{
if(str.charAt(x)=='{')
depth++;
else
if(str.charAt(x)=='}')
depth--;
x++;
}
var.var = str.substring(varstart+2,x);
if(x<str.length())
x++;
var.outerEnd=x;
}
else
if((x<str.length())&&(str.charAt(x)=='['))
{
final int varstart=var.outerStart;
x++;
int depth=0;
while((x<str.length())
&&((str.charAt(x)!=']')||(depth>0)))
{
if(str.charAt(x)=='[')
depth++;
else
if(str.charAt(x)==']')
depth--;
x++;
}
var.var = str.substring(varstart+2,x);
var.isMathExpression=true;
if(x<str.length())
x++;
var.outerEnd=x;
}
else
{
while((x<str.length())&&((str.charAt(x)=='_')||Character.isLetterOrDigit(str.charAt(x))))
x++;
var.var = str.substring(var.outerStart+1,x);
var.outerEnd=x;
}
list.add(var);
x=str.indexOf('$',var.outerEnd);
}
return list;
}
protected String fillOutStatCode(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String stat, final XMLTag piece, final Map<String,Object> defined, final boolean debug)
{
if(!ignoreStats.contains(stat.toUpperCase().trim()))
{
try
{
return PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
String value;
if((E instanceof MOB) && (stat.equals("ABILITY")))
value = findOptionalString(E,ignoreStats,defPrefix,"HPMOD",piece,this.defined, debug);
else
value = findOptionalString(E,ignoreStats,defPrefix,stat,piece,this.defined, debug);
if(value != null)
{
E.setStat(stat, value);
if((defPrefix!=null)&&(defPrefix.length()>0))
addDefinition(defPrefix+stat,value,this.defined);
}
return value;
}
});
}
catch(final CMException e)
{
Log.errOut(e);
//should never happen
}
}
return null;
}
protected void fillOutStatCodes(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined)
{
final String[] statCodes = E.getStatCodes();
for (final String stat : statCodes)
{
fillOutStatCode(E,ignoreStats,defPrefix,stat,piece,defined, false);
}
}
protected void fillOutCopyStats(final Modifiable E, final Modifiable E2)
{
if((E2 instanceof MOB)&&(!((MOB)E2).isGeneric()))
{
for(final GenericBuilder.GenMOBCode stat : GenericBuilder.GenMOBCode.values())
{
if(stat != GenericBuilder.GenMOBCode.ABILITY) // because this screws up gen hit points
{
E.setStat(stat.name(), CMLib.coffeeMaker().getGenMobStat((MOB)E2,stat.name()));
}
}
}
else
if((E2 instanceof Item)&&(!((Item)E2).isGeneric()))
{
for(final GenericBuilder.GenItemCode stat : GenericBuilder.GenItemCode.values())
{
E.setStat(stat.name(),CMLib.coffeeMaker().getGenItemStat((Item)E2,stat.name()));
}
}
else
for(final String stat : E2.getStatCodes())
{
E.setStat(stat, E2.getStat(stat));
}
}
protected boolean fillOutCopyCodes(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String copyStatID = findOptionalStringNow(E,ignoreStats,defPrefix,"COPYOF",piece,defined, false);
if(copyStatID!=null)
{
final List<String> V=CMParms.parseCommas(copyStatID,true);
for(int v=0;v<V.size();v++)
{
String s = V.get(v);
if(s.startsWith("$"))
s=s.substring(1).trim();
final XMLTag statPiece =(XMLTag)defined.get(s.toUpperCase().trim());
if(statPiece == null)
{
Object o=CMClass.getMOBPrototype(s);
if(o==null)
o=CMClass.getItemPrototype(s);
if(o==null)
o=CMClass.getObjectOrPrototype(s);
if(!(o instanceof Modifiable))
throw new CMException("Invalid copystat: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final Modifiable E2=(Modifiable)o;
if(o instanceof MOB)
{
((MOB)E2).setBaseCharStats((CharStats)((MOB)o).baseCharStats().copyOf());
((MOB)E2).setBasePhyStats((PhyStats)((MOB)o).basePhyStats().copyOf());
((MOB)E2).setBaseState((CharState)((MOB)o).baseState().copyOf());
}
fillOutCopyStats(E,E2);
}
else
{
final XMLTag likePiece =(XMLTag)defined.get(s.toUpperCase().trim());
if(likePiece == null)
throw new CMException("Invalid copystat: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final BuildCallback callBack=new BuildCallback()
{
@Override
public void willBuild(final Environmental E2, final XMLTag XMLTag)
{
fillOutCopyStats(E,E2);
}
};
findItems(E,likePiece,defined,callBack);
findMobs(E,likePiece,defined,callBack);
findAbilities(E,likePiece,defined,callBack);
findExits(E,likePiece,defined,callBack);
}
}
return V.size()>0;
}
return false;
}
protected MOB buildMob(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
MOB M = null;
final List<String> ignoreStats=new XArrayList<String>();
boolean copyFilled = false;
if(classID.equalsIgnoreCase("catalog"))
{
final String name = findStringNow("NAME",piece,defined);
if((name == null)||(name.length()==0))
throw new CMException("Unable to build a catalog mob without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
M = CMLib.catalog().getCatalogMob(name);
if(M==null)
throw new CMException("Unable to find cataloged mob called '"+name+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
M=(MOB)M.copyOf();
CMLib.catalog().changeCatalogUsage(M,true);
addDefinition("MOB_CLASS",M.ID(),defined);
copyFilled=true;
}
else
{
M = CMClass.getMOB(classID);
if(M == null)
throw new CMException("Unable to build mob on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
addDefinition("MOB_CLASS",classID,defined);
if(M.isGeneric())
{
copyFilled = fillOutCopyCodes(M,ignoreStats,"MOB_",piece,defined);
String name = fillOutStatCode(M,ignoreStats,"MOB_","NAME",piece,defined, false);
if((!copyFilled) && ((name == null)||(name.length()==0)))
name = fillOutStatCode(M,ignoreStats,"MOB_","NAME",piece,defined, false);
if((!copyFilled) && ((name == null)||(name.length()==0)))
{
name = fillOutStatCode(M,ignoreStats,"MOB_","NAME",piece,defined, true);
if((!copyFilled) && ((name == null)||(name.length()==0)))
throw new CMException("Unable to build a mob without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
if((name != null)&&(name.length()>0))
M.setName(name);
}
}
final MOB mob=M;
addDefinition("MOB_NAME",M.Name(),defined);
if(!copyFilled)
M.baseCharStats().setMyRace(CMClass.getRace("StdRace"));
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(mob,ignoreStats,"MOB_","LEVEL",piece,this.defined, false);
if((value != null)&&(value.length()>0))
{
mob.setStat("LEVEL",value);
addDefinition("MOB_LEVEL",value,this.defined);
CMLib.leveler().fillOutMOB(mob,mob.basePhyStats().level());
CMLib.leveler().fillOutMOB(mob,mob.basePhyStats().level());
}
return value;
}
});
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(mob,ignoreStats,"MOB_","GENDER",piece,this.defined, false);
if((value != null)&&(value.length()>0))
{
mob.baseCharStats().setStat(CharStats.STAT_GENDER,value.charAt(0));
addDefinition("MOB_GENDER",value,this.defined);
}
else
mob.baseCharStats().setStat(CharStats.STAT_GENDER,CMLib.dice().rollPercentage()>50?'M':'F');
PostProcessAttempter(this.defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(mob,ignoreStats,"MOB_","RACE",piece,this.defined, false);
if((value != null)&&(value.length()>0))
{
mob.setStat("RACE",value);
addDefinition("MOB_RACE",value,this.defined);
Race R=CMClass.getRace(value);
if(R==null)
{
final List<Race> races=findRaces(mob,piece, this.defined);
if(races.size()>0)
R=races.get(CMLib.dice().roll(1, races.size(), -1));
}
if(R!=null)
R.setHeightWeight(mob.basePhyStats(),(char)mob.baseCharStats().getStat(CharStats.STAT_GENDER));
}
return value;
}
});
return value;
}
});
PostProcessAttempter(defined, new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final List<XMLLibrary.XMLTag> choices = getAllChoices(mob,ignoreStats,"MOB_","FACTION", piece, this.defined, true);
if((choices!=null)&&(choices.size()>0))
{
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
final String f = valPiece.getParmValue("ID");
final String v = valPiece.getParmValue("VALUE");
mob.addFaction(f, Integer.parseInt(v));
}
}
return "";
}
});
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","NAME","LEVEL","GENDER"}));
fillOutStatCodes(M,ignoreStats,"MOB_",piece,defined);
M.recoverCharStats();
M.recoverPhyStats();
M.recoverMaxState();
final List<Item> items = findItems(piece,defined);
for(int i=0;i<items.size();i++)
{
final Item I=items.get(i);
final boolean wearable = (I.phyStats().sensesMask()&PhyStats.SENSE_ITEMNOAUTOWEAR)==0;
M.addItem(I);
I.setSavable(true);
if(wearable)
I.wearIfPossible(M);
}
final List<Ability> aV = findAffects(M,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability A=aV.get(i);
A.setSavable(true);
M.addNonUninvokableEffect(A);
}
final List<Behavior> bV= findBehaviors(M,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
M.addBehavior(B);
}
final List<Ability> abV = findAbilities(M,piece,defined,null);
for(int i=0;i<abV.size();i++)
{
final Ability A=abV.get(i);
A.setSavable(true);
M.addAbility(A);
}
final ShopKeeper SK=CMLib.coffeeShops().getShopKeeper(M);
if(SK!=null)
{
final CoffeeShop shop=(SK instanceof Librarian)?((Librarian)SK).getBaseLibrary():SK.getShop();
final List<Triad<Environmental,Integer,Long>> iV = findShopInventory(M,piece,defined);
if(iV.size()>0)
shop.emptyAllShelves();
for(int i=0;i<iV.size();i++)
shop.addStoreInventory(iV.get(i).first,iV.get(i).second.intValue(),iV.get(i).third.intValue());
}
M.recoverCharStats();
M.recoverPhyStats();
M.recoverMaxState();
M.text();
M.setMiscText(M.text());
M.recoverCharStats();
M.recoverPhyStats();
M.recoverMaxState();
return M;
}
protected List<Exit> findExits(final Modifiable M,final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<Exit> V = new Vector<Exit>();
final String tagName="EXIT";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(M,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Exit: "+CMStrings.limit(valPiece.value(),80)+"...");
defineReward(M,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Exit E=buildExit(valPiece,defined);
if(callBack != null)
callBack.willBuild(E, valPiece);
V.add(E);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
// remember to check ROOMLINK_DIR for N,S,E,W,U,D,etc..
protected Exit buildExit(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final List<String> ignoreStats=new XArrayList<String>();
final String classID = findStringNow("class",piece,defined);
final Exit E = CMClass.getExit(classID);
if(E == null)
throw new CMException("Unable to build exit on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
addDefinition("EXIT_CLASS",classID,defined);
ignoreStats.add("CLASS");
fillOutCopyCodes(E,ignoreStats,"EXIT_",piece,defined);
fillOutStatCodes(E,ignoreStats,"EXIT_",piece,defined);
final List<Ability> aV = findAffects(E,piece,defined,null);
for(int i=0;i<aV.size();i++)
{
final Ability A=aV.get(i);
A.setSavable(true);
E.addNonUninvokableEffect(A);
}
final List<Behavior> bV= findBehaviors(E,piece,defined);
for(int i=0;i<bV.size();i++)
{
final Behavior B=bV.get(i);
B.setSavable(true);
E.addBehavior(B);
}
E.text();
E.setMiscText(E.text());
E.recoverPhyStats();
return E;
}
protected List<Triad<Environmental,Integer,Long>> findShopInventory(final Modifiable E,final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Triad<Environmental,Integer,Long>> V = new Vector<Triad<Environmental,Integer,Long>>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,"SHOPINVENTORY", piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag shopPiece = choices.get(c);
if(shopPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(shopPiece.getParmValue("VALIDATE")),shopPiece, defined))
continue;
final String baseNumber[] = { "1" };
final String basePrice[] = { "-1" };
try
{
final String baseStr=shopPiece.getParmValue("NUMBER");
if(baseStr != null)
baseNumber[0]=baseStr;
}
catch (final Exception e)
{
}
try
{
final String baseStr=shopPiece.getParmValue("PRICE");
if(baseStr != null)
basePrice[0]=baseStr;
}
catch (final Exception e)
{
}
final BuildCallback callBack=new BuildCallback()
{
@Override
public void willBuild(final Environmental E, final XMLTag XMLTag)
{
String numbStr=XMLTag.getParmValue("NUMBER");
if(numbStr == null)
numbStr=baseNumber[0];
int number;
try
{
number = CMath.parseIntExpression(strFilter(E, null, null, numbStr.trim(), piece, defined));
}
catch (final Exception e)
{
number = 1;
}
numbStr=XMLTag.getParmValue("PRICE");
if(numbStr == null)
numbStr=basePrice[0];
long price;
try
{
price = CMath.parseLongExpression(strFilter(E, null, null, numbStr.trim(), piece, defined));
}
catch (final Exception e)
{
price = -1;
}
V.add(new Triad<Environmental,Integer,Long>(E,Integer.valueOf(number),Long.valueOf(price)));
}
};
findItems(E,shopPiece,defined,callBack);
findMobs(E,shopPiece,defined,callBack);
findAbilities(E,shopPiece,defined,callBack);
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Set<String> getPrevouslyDefined(final Map<String,Object> defined, final String prefix)
{
final Set<String> prevSet=new HashSet<String>();
for(final String key : defined.keySet())
{
if(key.toUpperCase().startsWith(prefix.toUpperCase()))
prevSet.add(key.toUpperCase());
}
return prevSet;
}
protected void clearNewlyDefined(final Map<String,Object> defined, final Set<String> exceptSet, final String prefix)
{
final Set<String> clearSet=new HashSet<String>();
for(final String key : defined.keySet())
if(key.toUpperCase().startsWith(prefix.toUpperCase())
&& (!exceptSet.contains(key.toUpperCase()))
&& (!key.startsWith("_")))
clearSet.add(key);
for(final String key : clearSet)
defined.remove(key);
}
@Override
public List<Item> findItems(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
return findItems(null,piece, defined, null);
}
protected List<Item> findItems(final Modifiable E,final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<Item> V = new Vector<Item>();
final String tagName="ITEM";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Build Item: "+CMStrings.limit(valPiece.value(),80)+"...");
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
try
{
for(final Item I : buildItem(valPiece,defined))
{
if(callBack != null)
callBack.willBuild(I, valPiece);
V.add(I);
}
}
catch(final CMException e)
{
throw e;
}
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Item> findContents(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Item> V = new Vector<Item>();
final String tagName="CONTENT";
final List<XMLLibrary.XMLTag> choices = getAllChoices(null,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Found Content: "+valPiece.value());
V.addAll(findItems(valPiece,defined));
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected String getMetacraftFilter(String recipe, final XMLTag piece, final Map<String,Object> defined, final Triad<Integer,Integer,Class<?>[]> filter) throws CMException
{
int levelLimit=-1;
int levelFloor=-1;
Class<?>[] deriveClasses=new Class[0];
final Map.Entry<Character, String>[] otherParms=CMStrings.splitMulti(recipe, splitters);
recipe=otherParms[0].getValue();
if(otherParms.length==1)
return recipe;
for(int i=1;i<otherParms.length;i++)
{
if(otherParms[i].getKey().charValue()=='<')
{
final String lvlStr=strFilterNow(null,null,null,otherParms[i].getValue().trim(),piece, defined);
if(CMath.isMathExpression(lvlStr))
{
levelLimit=CMath.parseIntExpression(lvlStr);
if((levelLimit==0)||(levelLimit<levelFloor))
levelLimit=-1;
}
}
else
if(otherParms[i].getKey().charValue()=='>')
{
final String lvlStr=strFilterNow(null,null,null,otherParms[i].getValue().trim(),piece, defined);
if(CMath.isMathExpression(lvlStr))
{
levelFloor=CMath.parseIntExpression(lvlStr);
if((levelFloor==0)||((levelFloor>levelLimit)&&(levelLimit>0)))
levelFloor=-1;
}
}
else
if(otherParms[i].getKey().charValue()=='=')
{
final String classStr=strFilterNow(null,null,null,otherParms[i].getValue().trim(),piece, defined);
final Object O=CMClass.getItemPrototype(classStr);
if(O!=null)
{
deriveClasses=Arrays.copyOf(deriveClasses, deriveClasses.length+1);
deriveClasses[deriveClasses.length-1]=O.getClass();
}
else
throw new CMException("Unknown metacraft class= "+classStr);
}
}
if(levelLimit>0)
filter.first=Integer.valueOf(levelLimit);
if(levelFloor>0)
filter.second=Integer.valueOf(levelFloor);
if(deriveClasses.length>0)
filter.third=deriveClasses;
return recipe;
}
@SuppressWarnings("unchecked")
protected List<ItemCraftor.ItemKeyPair> craftAllOfThisRecipe(final ItemCraftor skill, final int material, final Map<String,Object> defined)
{
List<ItemCraftor.ItemKeyPair> skillContents=(List<ItemCraftor.ItemKeyPair>)defined.get("____COFFEEMUD_"+skill.ID()+"_"+material+"_true");
if(skillContents==null)
{
if(material>=0)
skillContents=skill.craftAllItemSets(material, true);
else
skillContents=skill.craftAllItemSets(true);
if(skillContents==null)
return null;
defined.put("____COFFEEMUD_"+skill.ID()+"_"+material+"_true",skillContents);
}
final List<ItemCraftor.ItemKeyPair> skillContentsCopy=new Vector<ItemCraftor.ItemKeyPair>(skillContents.size());
skillContentsCopy.addAll(skillContents);
return skillContentsCopy;
}
protected boolean checkMetacraftItem(final Item I, final Triad<Integer,Integer,Class<?>[]> filter)
{
final int levelLimit=filter.first.intValue();
final int levelFloor=filter.second.intValue();
final Class<?>[] deriveClasses=filter.third;
if(((levelLimit>0) && (I.basePhyStats().level() > levelLimit))
||((levelFloor>0) && (I.basePhyStats().level() < levelFloor)))
return false;
if(deriveClasses.length==0)
return true;
for(final Class<?> C : deriveClasses)
{
if(C.isAssignableFrom(I.getClass()))
return true;
}
return false;
}
protected List<Item> buildItem(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final Map<String,Object> preContentDefined = new SHashtable<String,Object>(defined);
final String classID = findStringNow("class",piece,defined);
final List<Item> contents = new Vector<Item>();
final List<String> ignoreStats=new XArrayList<String>();
final int senseFlag = CMath.s_bool(findOptionalStringNow(null,null,null,"nowear",piece,defined,false)) ? PhyStats.SENSE_ITEMNOAUTOWEAR : 0;
if(classID.toLowerCase().startsWith("metacraft"))
{
final String classRest=classID.substring(9).toLowerCase().trim();
final Triad<Integer,Integer,Class<?>[]> filter = new Triad<Integer,Integer,Class<?>[]>(Integer.valueOf(-1),Integer.valueOf(-1),new Class<?>[0]);
String recipe="anything";
if(classRest.startsWith(":"))
{
recipe=getMetacraftFilter(classRest.substring(1).trim(), piece, defined, filter);
}
else
{
recipe = findStringNow("NAME",piece,defined);
if((recipe == null)||(recipe.length()==0))
throw new CMException("Unable to metacraft with malformed class Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
final String materialStr = findOptionalStringNow(null,null,null,"material",piece,defined, false);
int material=-1;
if(materialStr!=null)
material = RawMaterial.CODES.FIND_IgnoreCase(materialStr);
final List<ItemCraftor> craftors=new Vector<ItemCraftor>();
for(final Enumeration<Ability> e=CMClass.abilities();e.hasMoreElements();)
{
final Ability A=e.nextElement();
if(A instanceof ItemCraftor)
craftors.add((ItemCraftor)A);
}
if(recipe.equalsIgnoreCase("anything"))
{
final long startTime=System.currentTimeMillis();
while((contents.size()==0)&&((System.currentTimeMillis()-startTime)<1000))
{
final ItemCraftor skill=craftors.get(CMLib.dice().roll(1,craftors.size(),-1));
if(skill.fetchRecipes().size()>0)
{
final List<ItemCraftor.ItemKeyPair> skillContents=craftAllOfThisRecipe(skill,material,defined);
if(skillContents.size()==0) // preliminary error messaging, just for the craft skills themselves
Log.errOut("MUDPercolator","Tried metacrafting anything, got "+Integer.toString(skillContents.size())+" from "+skill.ID());
else
for(int i=skillContents.size()-1;i>=0;i--)
{
final Item I=skillContents.get(i).item;
if(!checkMetacraftItem(I, filter))
skillContents.remove(i);
}
if(skillContents.size()>0)
{
final Item I=(Item)skillContents.get(CMLib.dice().roll(1,skillContents.size(),-1)).item.copyOf();
contents.add(I);
}
}
}
}
else
if(recipe.toLowerCase().startsWith("any-"))
{
List<ItemCraftor.ItemKeyPair> skillContents=null;
recipe=recipe.substring(4).trim();
for(final ItemCraftor skill : craftors)
{
if(skill.ID().equalsIgnoreCase(recipe))
{
skillContents=craftAllOfThisRecipe(skill,material,defined);
if((skillContents==null)||(skillContents.size()==0)) // this is just for checking the skills themselves
Log.errOut("MUDPercolator","Tried metacrafting any-"+recipe+", got "+Integer.toString(contents.size())+" from "+skill.ID());
else
for(int i=skillContents.size()-1;i>=0;i--)
{
final Item I=skillContents.get(i).item;
if(!checkMetacraftItem(I, filter))
skillContents.remove(i);
}
break;
}
}
if((skillContents!=null)&&(skillContents.size()>0))
{
final Item I=(Item)skillContents.get(CMLib.dice().roll(1,skillContents.size(),-1)).item.copyOf();
contents.add(I);
}
}
else
if(recipe.toLowerCase().startsWith("all"))
{
List<ItemCraftor.ItemKeyPair> skillContents=null;
recipe=recipe.substring(3).startsWith("-")?recipe.substring(4).trim():"";
for(final ItemCraftor skill : craftors)
{
if(skill.ID().equalsIgnoreCase(recipe)||(recipe.length()==0))
{
skillContents=craftAllOfThisRecipe(skill,material,defined);
if((skillContents==null)||(skillContents.size()==0)) // this is just for checking the skills themselves
Log.errOut("MUDPercolator","Tried metacrafting any-"+recipe+", got "+Integer.toString(contents.size())+" from "+skill.ID());
else
for(int i=skillContents.size()-1;i>=0;i--)
{
final Item I=skillContents.get(i).item;
if(!checkMetacraftItem(I, filter))
skillContents.remove(i);
}
while((skillContents!=null)&&(skillContents.size()>0))
{
final Item I=(Item)skillContents.remove(0).item.copyOf();
contents.add(I);
}
if(recipe.length()>0)
break;
}
}
}
else
{
for(final ItemCraftor skill : craftors)
{
final List<List<String>> V=skill.matchingRecipeNames(recipe,false);
if((V!=null)&&(V.size()>0))
{
ItemCraftor.ItemKeyPair pair;
if(material>=0)
pair=skill.craftItem(recipe,material,true, false);
else
pair=skill.craftItem(recipe,-1,true, false);
if(pair!=null)
{
contents.add(pair.item);
break;
}
}
}
for(int i=contents.size()-1;i>=0;i--)
{
final Item I=contents.get(i);
if(!checkMetacraftItem(I, filter))
contents.remove(i);
}
if(contents.size()==0)
{
for(final ItemCraftor skill : craftors)
{
final List<List<String>> V=skill.matchingRecipeNames(recipe,true);
if((V!=null)&&(V.size()>0))
{
ItemCraftor.ItemKeyPair pair;
if(material>=0)
pair=skill.craftItem(recipe,material,true, false);
else
pair=skill.craftItem(recipe,0,true, false);
if(pair!=null)
{
contents.add(pair.item);
break;
}
}
}
}
for(int i=contents.size()-1;i>=0;i--)
{
final Item I=contents.get(i);
if(!checkMetacraftItem(I, filter))
contents.remove(i);
}
}
if(contents.size()==0)
{
if(filter.equals(emptyMetacraftFilter))
throw new CMException("Unable to metacraft an item called '"+recipe+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
else
return new ArrayList<Item>(0);
}
for(final Item I : contents)
{
addDefinition("ITEM_CLASS",I.ID(),defined);
addDefinition("ITEM_NAME",I.Name(),defined); // define so we can mess with it
addDefinition("ITEM_LEVEL",""+I.basePhyStats().level(),defined); // define so we can mess with it
fillOutStatCode(I,ignoreStats,"ITEM_","NAME",piece,defined, false);
fillOutStatCode(I,ignoreStats,"ITEM_","LEVEL",piece,defined, false);
}
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","MATERIAL","NAME","LEVEL"}));
}
else
if(classID.equalsIgnoreCase("catalog"))
{
final String name = findStringNow("NAME",piece,defined);
if((name == null)||(name.length()==0))
throw new CMException("Unable to build a catalog item without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
Item I = CMLib.catalog().getCatalogItem(name);
if(I==null)
throw new CMException("Unable to find cataloged item called '"+name+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
I=(Item)I.copyOf();
CMLib.catalog().changeCatalogUsage(I,true);
contents.add(I);
addDefinition("ITEM_CLASS",I.ID(),defined);
addDefinition("ITEM_NAME",I.Name(),defined); // define so we can mess with it
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","NAME"}));
}
else
{
final Item I = CMClass.getItem(classID);
if(I == null)
throw new CMException("Unable to build item on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
contents.add(I);
addDefinition("ITEM_CLASS",classID,defined);
if(I.isGeneric())
{
final boolean filledOut = fillOutCopyCodes(I,ignoreStats,"ITEM_",piece,defined);
final String name = fillOutStatCode(I,ignoreStats,"ITEM_","NAME",piece,defined, false);
if((!filledOut) && ((name == null)||(name.length()==0)))
throw new CMException("Unable to build an item without a name, Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
if((name != null)&&(name.length()>0))
I.setName(name);
}
ignoreStats.addAll(Arrays.asList(new String[]{"CLASS","NAME"}));
addDefinition("ITEM_NAME",I.Name(),defined); // define so we can mess with it
}
final int contentSize=contents.size();
for(int it=0;it<contentSize;it++) // no iterator, please!!
{
final Item I=contents.get(it);
fillOutStatCodes(I,ignoreStats,"ITEM_",piece,defined);
I.recoverPhyStats();
CMLib.itemBuilder().balanceItemByLevel(I);
I.recoverPhyStats();
fillOutStatCodes(I,ignoreStats,"ITEM_",piece,defined);
I.recoverPhyStats();
if(I instanceof Container)
{
final List<Item> V= findContents(piece,new SHashtable<String,Object>(preContentDefined));
for(int i=0;i<V.size();i++)
{
final Item I2=V.get(i);
I2.setContainer((Container)I);
contents.add(I2);
}
}
{
final List<Ability> V= findAffects(I,piece,defined,null);
for(int i=0;i<V.size();i++)
{
final Ability A=V.get(i);
A.setSavable(true);
I.addNonUninvokableEffect(A);
}
}
final List<Behavior> V = findBehaviors(I,piece,defined);
for(int i=0;i<V.size();i++)
{
final Behavior B=V.get(i);
B.setSavable(true);
I.addBehavior(B);
}
I.recoverPhyStats();
I.text();
I.setMiscText(I.text());
I.recoverPhyStats();
I.phyStats().setSensesMask(I.phyStats().sensesMask()|senseFlag);
}
return contents;
}
protected List<Ability> findAffects(final Modifiable E, final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
return findAbilities(E,"AFFECT",piece,defined,callBack);
}
protected List<Ability> findAbilities(final Modifiable E, final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
return findAbilities(E,"ABILITY",piece,defined,callBack);
}
protected List<Ability> findAbilities(final Modifiable E, final String tagName, final XMLTag piece, final Map<String,Object> defined, final BuildCallback callBack) throws CMException
{
try
{
final List<Ability> V = new Vector<Ability>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE")
&& !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Ability A=buildAbility(E,valPiece,defined);
if(callBack != null)
callBack.willBuild(A, valPiece);
V.add(A);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Behavior> findBehaviors(final Modifiable E,final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Behavior> V = new Vector<Behavior>();
final String tagName="BEHAVIOR";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Behavior B=buildBehavior(E,valPiece,defined);
V.add(B);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Race> findRaces(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException, PostProcessException
{
final List<Race> V = new Vector<Race>();
final String tagName="RACE";
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,null,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,null,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final Race R=buildGenRace(E,valPiece,defined);
V.add(R);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
protected Ability buildAbility(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
Ability A=CMClass.getAbility(classID);
if(A == null)
A=CMClass.findAbility(classID);
if(A == null)
throw new CMException("Unable to build ability on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final Ability aA=A;
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(E,null,null,"PARMS",piece,this.defined, false);
if(value != null)
aA.setMiscText(value);
return value;
}
});
return A;
}
protected Behavior buildBehavior(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
Behavior B=CMClass.getBehavior(classID);
if(B == null)
B=CMClass.findBehavior(classID);
if(B == null)
throw new CMException("Unable to build behavior on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final Behavior bB=B;
PostProcessAttempter(defined,new PostProcessAttempt()
{
@Override
public String attempt() throws CMException, PostProcessException
{
final String value = findOptionalString(E,null,null,"PARMS",piece,this.defined, false);
if(value != null)
bB.setParms(value);
return value;
}
});
return B;
}
protected List<AbilityMapping> findRaceAbles(final Modifiable E, final String tagName, final String prefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<AbilityMapping> V = new Vector<AbilityMapping>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,prefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,prefix,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
defineReward(E,null,prefix,valPiece.getParmValue("DEFINE"),valPiece,null,defined,true);
final Set<String> definedSet=getPrevouslyDefined(defined,tagName+"_");
final String classID = findStringNow("CLASS",valPiece,defined);
Ability A=CMClass.getAbility(classID);
if(A == null)
A=CMClass.findAbility(classID);
if(A == null)
throw new CMException("Unable to build ability on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
defined.put(prefix+"CLASS", classID);
final AbilityMapping mapA=CMLib.ableMapper().newAbilityMapping().ID(classID);
String value;
value=findOptionalStringNow(E, null, prefix, "PARMS", valPiece, defined, false);
if(value != null)
{
mapA.defaultParm(value);
defined.put(prefix+"PARMS", value);
}
value=findOptionalStringNow(E, null, prefix, "PROFF", valPiece, defined, false);
if(value != null)
{
mapA.defaultProficiency(CMath.parseIntExpression(value));
defined.put(prefix+"PROFF", Integer.valueOf(mapA.defaultProficiency()));
}
value=findOptionalStringNow(E, null, prefix, "LEVEL", valPiece, defined, false);
if(value != null)
{
mapA.qualLevel(CMath.parseIntExpression(value));
defined.put(prefix+"LEVEL", Integer.valueOf(mapA.qualLevel()));
}
value=findOptionalStringNow(E, null, prefix, "QUALIFY", valPiece, defined, false);
if(value != null)
{
mapA.autoGain(!CMath.s_bool(value));
defined.put(prefix+"QUALIFY", value);
}
V.add(mapA);
clearNewlyDefined(defined, definedSet, tagName+"_");
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected List<Item> getRaceItems(final Modifiable E, final String tagName, final String prefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
final List<Item> V = new Vector<Item>();
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,null,prefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
return V;
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MUDPercolator","Found Race Item: "+valPiece.value());
V.addAll(findItems(valPiece,defined));
}
return V;
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object type: "+pe.getMessage(),pe);
}
}
protected Race buildGenRace(final Modifiable E, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String classID = findStringNow("class",piece,defined);
Race R=CMClass.getRace(classID);
if( R != null)
return R;
R=(Race)CMClass.getRace("GenRace").copyOf();
int numStatsFound=0;
for(final String stat : R.getStatCodes())
{
try
{
if(findOptionalString(null, null, null, stat, piece, defined, false)!=null)
numStatsFound++;
}
catch(final PostProcessException pe)
{
numStatsFound++;
}
}
if(numStatsFound<5)
throw new CMException("Too few fields to build race on classID '"+classID+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
R.setRacialParms("<RACE><ID>"+CMStrings.capitalizeAndLower(classID)+"</ID><NAME>"+CMStrings.capitalizeAndLower(classID)+"</NAME></RACE>");
CMClass.addRace(R);
addDefinition("RACE_CLASS",R.ID(),defined); // define so we can mess with it
R.setStat("NAME", findStringNow("name",piece,defined));
addDefinition("RACE_NAME",R.name(),defined); // define so we can mess with it
final List<String> ignoreStats=new XArrayList<String>(new String[]{"CLASS","NAME"});
final List<Item> raceWeapons=getRaceItems(E,"WEAPON","RACE_WEAPON_",piece,defined);
if(raceWeapons.size()>0)
{
final Item I=raceWeapons.get(CMLib.dice().roll(1, raceWeapons.size(), -1));
R.setStat("WEAPONCLASS", I.ID());
R.setStat("WEAPONXML", I.text());
}
ignoreStats.addAll(Arrays.asList(new String[]{"WEAPONCLASS","WEAPONXML"}));
final List<Item> raceResources=getRaceItems(E,"RESOURCES","RACE_RESOURCE_",piece,defined);
R.setStat("NUMRSC", ""+raceResources.size());
for(int i=0;i<raceResources.size();i++)
{
final Item I=raceResources.get(i);
R.setStat("GETRSCID"+i, I.ID());
R.setStat("GETRSCPARM"+i, ""+I.text());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMRSC","GETRSCID","GETRSCPARM"}));
final List<Item> raceOutfit=getRaceItems(E,"OUTFIT","RACE_RESOURCE_",piece,defined);
R.setStat("NUMOFT", ""+raceOutfit.size());
for(int i=0;i<raceOutfit.size();i++)
{
final Item I=raceOutfit.get(i);
R.setStat("GETOFTID"+i, I.ID());
R.setStat("GETOFTPARM"+i, ""+I.text());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMOFT","GETOFTID","GETOFTPARM"}));
final List<AbilityMapping> rables = findRaceAbles(E,"ABILITY","RACE_ABLE_",piece,defined);
R.setStat("NUMRABLE", ""+rables.size());
for(int i=0;i<rables.size();i++)
{
final AbilityMapping ableMap=rables.get(i);
R.setStat("GETRABLE"+i, ableMap.abilityID());
R.setStat("GETRABLEPROF"+i, ""+ableMap.defaultProficiency());
R.setStat("GETRABLEQUAL"+i, ""+(!ableMap.autoGain()));
R.setStat("GETRABLELVL"+i, ""+ableMap.qualLevel());
R.setStat("GETRABLEPARM"+i, ableMap.defaultParm());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMRABLE","GETRABLE","GETRABLEPROF","GETRABLEQUAL","GETRABLELVL","GETRABLEPARM"}));
final List<AbilityMapping> cables = findRaceAbles(E,"CULTUREABILITY","RACE_CULT_ABLE_",piece,defined);
R.setStat("NUMCABLE", ""+cables.size());
for(int i=0;i<cables.size();i++)
{
final AbilityMapping ableMap=cables.get(i);
R.setStat("GETCABLE"+i, ableMap.abilityID());
R.setStat("GETCABLEPROF"+i, ""+ableMap.defaultProficiency());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMCABLE","GETCABLE","GETCABLEPROF"}));
final List<AbilityMapping> reffs = findRaceAbles(E,"AFFECT","RACE_EFFECT_",piece,defined);
R.setStat("NUMREFF", ""+reffs.size());
for(int i=0;i<reffs.size();i++)
{
final AbilityMapping ableMap=reffs.get(i);
R.setStat("GETREFF"+i, ableMap.abilityID());
R.setStat("GETREFFPARM"+i, ""+ableMap.defaultParm());
R.setStat("GETREFFLVL"+i, ""+ableMap.qualLevel());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMREFF","GETREFF","GETREFFPARM","GETREFFLVL"}));
final List<AbilityMapping> iables = findRaceAbles(E,"IMMUNITY","RACE_IMMUNITY_",piece,defined);
R.setStat("NUMIABLE", ""+reffs.size());
for(int i=0;i<iables.size();i++)
{
final AbilityMapping ableMap=reffs.get(i);
R.setStat("GETIABLE"+i, ableMap.abilityID());
}
ignoreStats.addAll(Arrays.asList(new String[]{"NUMIABLE","GETIABLE"}));
fillOutStatCodes(R,ignoreStats,"RACE_",piece,defined);
CMLib.database().DBCreateRace(R.ID(),R.racialParms());
return R;
}
protected void addDefinition(String definition, final String value, final Map<String,Object> defined)
{
definition=definition.toUpperCase().trim();
defined.put(definition, value);
if(definition.toUpperCase().endsWith("S"))
definition+="ES";
else
definition+="S";
final String def = (String)defined.get(definition);
if(def==null)
defined.put(definition, value);
else defined.put(definition, def+","+value);
}
protected String findOptionalStringNow(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined, final boolean debug)
{
try
{
return findOptionalString(E,ignoreStats,defPrefix,tagName, piece, defined, false);
}
catch(final PostProcessException x)
{
if(debug)
Log.errOut(x);
return null;
}
}
protected String findOptionalString(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined, final boolean debug) throws PostProcessException
{
try
{
return findString(E,ignoreStats,defPrefix,tagName, piece, defined);
}
catch(final CMException x)
{
if(debug)
Log.errOut(x);
return null;
}
}
@Override
public void defineReward(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
defineReward(null, null, null,piece,piece.value(),defined);
}
protected void defineReward(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final String value, final Map<String,Object> defined) throws CMException
{
try
{
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("DEFINE"),piece,value,defined,true);
}
catch(final PostProcessException pe)
{
throw new CMException("Post-processing not permitted: "+pe.getMessage(),pe);
}
}
@Override
public void preDefineReward(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
preDefineReward(null,null,null,piece,defined);
}
protected void preDefineReward(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("PREDEFINE"),piece,piece.value(),defined,false);
}
catch(final PostProcessException pe)
{
throw new CMException("Post-processing not permitted: "+pe.getMessage(),pe);
}
}
protected void defineReward(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String defineString, final XMLTag piece, final Object value, final Map<String,Object> defined, final boolean recurseAllowed) throws CMException, PostProcessException
{
if((defineString!=null)&&(defineString.trim().length()>0))
{
final List<String> V=CMParms.parseCommas(defineString,true);
for (String defVar : V)
{
Object definition=value;
final int x=defVar.indexOf('=');
if(x==0)
continue;
if(x>0)
{
definition=defVar.substring(x+1).trim();
defVar=defVar.substring(0,x).toUpperCase().trim();
switch(defVar.charAt(defVar.length()-1))
{
case '+':
case '-':
case '*':
case '/':
{
final char plusMinus=defVar.charAt(defVar.length()-1);
defVar=defVar.substring(0,defVar.length()-1).trim();
String oldVal=(String)defined.get(defVar.toUpperCase().trim());
if((oldVal==null)||(oldVal.trim().length()==0))
oldVal="0";
definition=oldVal+plusMinus+definition;
break;
}
}
}
if(definition==null)
definition="!";
if(definition instanceof String)
{
definition=strFilter(E,ignoreStats,defPrefix,(String)definition,piece, defined);
if(CMath.isMathExpression((String)definition))
definition=Integer.toString(CMath.s_parseIntExpression((String)definition));
}
if(defVar.trim().length()>0)
defined.put(defVar.toUpperCase().trim(), definition);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","DEFINE:"+defVar.toUpperCase().trim()+"="+definition);
}
}
final XMLTag parentPiece = piece.parent();
if((parentPiece!=null)&&(parentPiece.tag().equalsIgnoreCase(piece.tag()))&&(recurseAllowed))
defineReward(E,ignoreStats,defPrefix,parentPiece.getParmValue("DEFINE"),parentPiece,value,defined,recurseAllowed);
}
protected String findStringNow(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
return findString(E,ignoreStats,defPrefix,tagName,piece,defined);
}
catch(final PostProcessException pe)
{
throw new CMException("Post processing not permitted",pe);
}
}
protected String replaceLineStartsWithIgnoreCase(final String wholeText, final String lineStarter, final String fullNewLine)
{
final int x=wholeText.toLowerCase().indexOf(lineStarter.toLowerCase());
if(x>0)
{
int y=wholeText.indexOf('\n',x+1);
final int z=wholeText.indexOf('\r',x+1);
if((y<x)||((z>x)&&(z<y)))
y=z;
if(y>x)
return wholeText.substring(0,x)+fullNewLine+wholeText.substring(y);
}
return wholeText;
}
protected String findString(final Modifiable E, final List<String> ignoreStats, final String defPrefix, String tagName, XMLTag piece, final Map<String,Object> defined) throws CMException,PostProcessException
{
tagName=tagName.toUpperCase().trim();
if(tagName.startsWith("SYSTEM_RANDOM_NAME:"))
{
final String[] split=tagName.substring(19).split("-");
if((split.length==2)&&(CMath.isInteger(split[0]))&&(CMath.isInteger(split[1])))
return CMLib.login().generateRandomName(CMath.s_int(split[0]), CMath.s_int(split[1]));
throw new CMException("Bad random name range in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
else
if(tagName.equals("ROOM_AREAGATE"))
{
if(E instanceof Environmental)
{
final Room R=CMLib.map().roomLocation((Environmental)E);
if(R!=null)
{
boolean foundOne=false;
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
final Room R2=R.getRoomInDir(d);
foundOne=(R2!=null) || foundOne;
if((R2!=null) && (R2.roomID().length()>0) && (R.getArea()!=R2.getArea()))
return CMLib.directions().getDirectionName(d);
}
if(!foundOne)
throw new PostProcessException("No exits at all on on object "+R.roomID()+" in variable '"+tagName+"'");
}
}
return "";
}
if(defPrefix != null)
{
final Object asPreviouslyDefined = defined.get((defPrefix+tagName).toUpperCase());
if(asPreviouslyDefined instanceof String)
return strFilter(E,ignoreStats,defPrefix,(String)asPreviouslyDefined,piece, defined);
}
final String asParm = piece.getParmValue(tagName);
if(asParm != null)
return strFilter(E,ignoreStats,defPrefix,asParm,piece, defined);
final Object asDefined = defined.get(tagName);
if(asDefined instanceof String)
return (String)asDefined;
final String contentload = piece.getParmValue("CONTENT_LOAD");
if((contentload!=null)
&&(contentload.length()>0))
{
final CMFile file = new CMFile(contentload,null,CMFile.FLAG_LOGERRORS|CMFile.FLAG_FORCEALLOW);
if(file.exists() && file.canRead())
return strFilter(E, ignoreStats, defPrefix,file.text().toString(), piece, defined);
else
throw new CMException("Bad content_load filename in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
String questTemplateLoad = piece.getParmValue("QUEST_TEMPLATE_ID");
if((questTemplateLoad!=null)
&&(questTemplateLoad.length()>0))
{
piece.parms().remove("QUEST_TEMPLATE_ID"); // once only, please
questTemplateLoad = strFilter(E,ignoreStats,defPrefix,questTemplateLoad,piece, defined);
final CMFile file = new CMFile(Resources.makeFileResourceName("quests/templates/"+questTemplateLoad.trim()+".quest"),null,CMFile.FLAG_LOGERRORS|CMFile.FLAG_FORCEALLOW);
if(file.exists() && file.canRead())
{
final String rawFileText = file.text().toString();
final int endX=rawFileText.lastIndexOf("#!QUESTMAKER_END_SCRIPT");
if(endX > 0)
{
final int lastCR = rawFileText.indexOf('\n', endX);
final int lastEOF = rawFileText.indexOf('\r', endX);
final int endScript = lastCR > endX ? (lastCR < lastEOF ? lastCR : lastEOF): lastEOF;
final List<String> wizList = Resources.getFileLineVector(new StringBuffer(rawFileText.substring(0, endScript).trim()));
String cleanedFileText = rawFileText.substring(endScript).trim();
cleanedFileText = CMStrings.replaceAll(cleanedFileText, "$#AUTHOR", "CoffeeMud");
final String duration=this.findOptionalString(E, ignoreStats, defPrefix, "DURATION", piece, defined, false);
if((duration != null) && (duration.trim().length()>0))
cleanedFileText = this.replaceLineStartsWithIgnoreCase(cleanedFileText, "set duration", "SET DURATION "+duration);
final String expiration=this.findOptionalString(E, ignoreStats, defPrefix, "EXPIRATION", piece, defined, false);
if((expiration != null) && (expiration.trim().length()>0))
cleanedFileText = this.replaceLineStartsWithIgnoreCase(cleanedFileText, "set duration", "SET EXPIRATION "+expiration);
for(final String wiz : wizList)
{
if(wiz.startsWith("#$"))
{
final int x=wiz.indexOf('=');
if(x>0)
{
final String var=wiz.substring(1,x);
if(cleanedFileText.indexOf(var)>0)
{
final String findVar=wiz.substring(2,x);
final String value=findStringNow(findVar, piece, defined);
cleanedFileText=CMStrings.replaceAll(cleanedFileText,var,value);
}
}
}
}
return cleanedFileText;
}
else
throw new CMException("Corrupt quest_template in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
else
throw new CMException("Bad quest_template_id in '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
XMLTag processDefined=null;
if(asDefined instanceof XMLTag)
{
piece=(XMLTag)asDefined;
processDefined=piece;
tagName=piece.tag();
}
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,ignoreStats,defPrefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
throw new CMException("Unable to find tag '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
StringBuffer finalValue = new StringBuffer("");
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final String value=strFilter(E,ignoreStats,defPrefix,valPiece.value(),valPiece, defined);
if(processDefined!=valPiece)
defineReward(E,ignoreStats,defPrefix,valPiece.getParmValue("DEFINE"),valPiece,value,defined,true);
String action = valPiece.getParmValue("ACTION");
if(action==null)
finalValue.append(" ").append(value);
else
{
action=action.toUpperCase().trim();
if((action.length()==0)||(action.equals("APPEND")))
finalValue.append(" ").append(value);
else
if(action.equals("REPLACE"))
finalValue = new StringBuffer(value);
else
if(action.equals("PREPEND"))
finalValue.insert(0,' ').insert(0,value);
else
throw new CMException("Unknown action '"+action+" on subPiece "+valPiece.tag()+" on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
}
final String finalFinalValue=finalValue.toString().trim();
if(processDefined!=null)
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("DEFINE"),processDefined,finalFinalValue,defined,true);
return finalFinalValue;
}
@Override
public String buildQuestScript(final XMLTag piece, final Map<String,Object> defined, final Modifiable E) throws CMException
{
final List<String> ignore=new ArrayList<String>();
try
{
return this.findString(E, ignore, null, "QUEST", piece, defined);
}
catch(final PostProcessException pe)
{
throw new CMException("Post processing not permitted",pe);
}
}
protected Object findObject(final Modifiable E, final List<String> ignoreStats, final String defPrefix, String tagName, XMLTag piece, final Map<String,Object> defined) throws CMException,PostProcessException
{
tagName=tagName.toUpperCase().trim();
if(defPrefix != null)
{
final Object asPreviouslyDefined = defined.get((defPrefix+tagName).toUpperCase());
if(asPreviouslyDefined instanceof String)
return strFilter(E,ignoreStats,defPrefix,(String)asPreviouslyDefined,piece, defined);
if(!(asPreviouslyDefined instanceof XMLTag))
return asPreviouslyDefined;
}
final String asParm = piece.getParmValue(tagName);
if(asParm != null)
return strFilter(E,ignoreStats,defPrefix,asParm,piece, defined);
final Object asDefined = defined.get(tagName);
if((!(asDefined instanceof XMLTag))
&&(!(asDefined instanceof String))
&&(asDefined != null))
return asDefined;
XMLTag processDefined=null;
if(asDefined instanceof XMLTag)
{
piece=(XMLTag)asDefined;
processDefined=piece;
tagName=piece.tag();
}
final List<XMLLibrary.XMLTag> choices = getAllChoices(E,ignoreStats,defPrefix,tagName, piece, defined,true);
if((choices==null)||(choices.size()==0))
throw new CMException("Unable to find tag '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
final List<Object> finalValues = new ArrayList<Object>();
for(int c=0;c<choices.size();c++)
{
final XMLTag valPiece = choices.get(c);
if(valPiece.parms().containsKey("VALIDATE") && !testCondition(E,null,null,CMLib.xml().restoreAngleBrackets(valPiece.getParmValue("VALIDATE")),valPiece, defined))
continue;
final String valueStr=valPiece.value().toUpperCase().trim();
final Object value;
if(valueStr.startsWith("SELECT:"))
{
final List<Map<String,Object>> sel=this.doMQLSelectObjs(E, ignoreStats, defPrefix, valueStr, valPiece, defined);
value=sel;
finalValues.addAll(sel);
}
else
if(valueStr.equals("MOB"))
{
final List<MOB> objs = this.findMobs(E, valPiece, defined, null);
value=objs;
finalValues.addAll(objs);
}
else
if(valueStr.equals("ITEM"))
{
final List<Item> objs = this.findItems(E, valPiece, defined, null);
value=objs;
finalValues.addAll(objs);
}
else
if(valueStr.equals("ABILITY"))
{
final List<Ability> objs = this.findAbilities(E, valPiece, defined, null);
value=objs;
finalValues.addAll(objs);
}
else
{
try
{
final List<Object> objs = parseMQLFrom(valueStr, valueStr, E, ignoreStats, defPrefix, valPiece, defined);
value=objs;
finalValues.addAll(objs);
}
catch(final CMException e)
{
throw new CMException("Unable to produce '"+tagName+"' on piece '"+piece.tag()+"', Data: "+CMStrings.limit(piece.value(),100)+":"+e.getMessage());
}
}
if(processDefined!=valPiece)
defineReward(E,ignoreStats,defPrefix,valPiece.getParmValue("DEFINE"),valPiece,value,defined,true);
}
if(processDefined!=null)
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("DEFINE"),processDefined,finalValues.size()==1?finalValues.get(0):finalValues,defined,true);
return finalValues.size()==1?finalValues.get(0):finalValues;
}
protected XMLTag processLikeParm(final String tagName, XMLTag piece, final Map<String,Object> defined) throws CMException
{
final String like = piece.getParmValue("LIKE");
if(like!=null)
{
final List<String> V=CMParms.parseCommas(like,true);
final XMLTag origPiece = piece;
piece=piece.copyOf();
for(int v=0;v<V.size();v++)
{
String s = V.get(v);
if(s.startsWith("$"))
s=s.substring(1).trim();
final XMLTag likePiece =(XMLTag)defined.get(s.toUpperCase().trim());
if((likePiece == null)||(!likePiece.tag().equalsIgnoreCase(tagName)))
throw new CMException("Invalid like: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
piece.contents().addAll(likePiece.contents());
piece.parms().putAll(likePiece.parms());
piece.parms().putAll(origPiece.parms());
}
}
return piece;
}
@Override
public List<XMLTag> getAllChoices(final String tagName, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
return getAllChoices(null,null,null,tagName,piece,defined,true);
}
catch(final PostProcessException pe)
{
throw new CMException("Unable to post process this object: "+pe.getMessage(),pe);
}
}
protected List<XMLTag> getAllChoices(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String tagName, final XMLTag piece, final Map<String,Object> defined, final boolean skipTest) throws CMException, PostProcessException
{
if((!skipTest)
&&(!testCondition(E,ignoreStats,defPrefix,CMLib.xml().restoreAngleBrackets(piece.getParmValue("CONDITION")),piece,defined)))
return new Vector<XMLTag>(1);
defineReward(E,ignoreStats,defPrefix,piece.getParmValue("PREDEFINE"),piece,piece.value(),defined,false); // does pre-define
final List<XMLTag> choices = new Vector<XMLTag>();
final String inserter = piece.getParmValue("INSERT");
if(inserter != null)
{
final String upperInserter = inserter.toUpperCase().trim();
if(upperInserter.startsWith("SELECT:"))
{
final List<Map<String,Object>> objs=this.doMQLSelectObjs(E, ignoreStats, defPrefix, upperInserter, piece, defined);
for(final Map<String,Object> m : objs)
{
for(final String key : m.keySet())
{
if(key.equalsIgnoreCase(tagName))
choices.add(CMLib.xml().createNewTag(tagName, this.convertMQLObjectToString(m.get(key))));
}
}
}
else
{
final List<String> V=CMParms.parseCommas(upperInserter,true);
for(int v=0;v<V.size();v++)
{
String s = V.get(v);
if(s.startsWith("$"))
s=s.substring(1).trim();
final XMLTag insertPiece =(XMLTag)defined.get(s.trim());
if(insertPiece == null)
throw new CMException("Undefined insert: '"+s+"' on piece '"+piece.tag()+"', Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
if(insertPiece.tag().equalsIgnoreCase(tagName))
choices.addAll(getAllChoices(E,ignoreStats,defPrefix,tagName,insertPiece,defined,false));
}
}
}
else
if(piece.tag().equalsIgnoreCase(tagName))
{
if((piece.parms().containsKey("LAYOUT")) && (piece.tag().equalsIgnoreCase("ROOM")) && (!defined.containsKey("ROOM_LAYOUT")))
return new XVector<XMLTag>(processLikeParm(tagName,piece,defined));
boolean container=false;
for(int p=0;p<piece.contents().size();p++)
{
final XMLTag ppiece=piece.contents().get(p);
if(ppiece.tag().equalsIgnoreCase(tagName))
{
container=true;
break;
}
}
if(!container)
return new XVector<XMLTag>(processLikeParm(tagName,piece,defined));
}
for(int p=0;p<piece.contents().size();p++)
{
final XMLTag subPiece = piece.contents().get(p);
if(subPiece.tag().equalsIgnoreCase(tagName))
choices.addAll(getAllChoices(E,ignoreStats,defPrefix,tagName,subPiece,defined,false));
}
return selectChoices(E,tagName,ignoreStats,defPrefix,choices,piece,defined);
}
protected boolean testCondition(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String condition, final XMLTag piece, final Map<String,Object> defined) throws PostProcessException
{
final Map<String,Object> fixed=new HashMap<String,Object>();
try
{
if(condition == null)
return true;
final List<Varidentifier> ids=parseVariables(condition);
for(final Varidentifier id : ids)
{
try
{
final String upperId=id.var.toUpperCase();
final boolean missingMobVarCondition;
if(defPrefix != null)
{
missingMobVarCondition = (defined!=null)
&&(upperId.startsWith(defPrefix))
&&(!defined.containsKey(upperId));
if(missingMobVarCondition)
{
XMLTag newPiece=piece;
while((newPiece.parent()!=null)&&(newPiece.tag().equals(piece.tag())))
newPiece=newPiece.parent();
fillOutStatCode(E, ignoreStats, defPrefix, id.var.substring(defPrefix.length()), newPiece, defined, false);
}
}
else
missingMobVarCondition = false;
String value;
if(upperId.startsWith("SELECT:"))
{
try
{
value=doMQLSelectString(E,null,null,id.var,piece,defined);
}
catch(final MQLException e)
{
value="";
}
return this.testCondition(E, ignoreStats, defPrefix, CMStrings.replaceAll(condition, condition.substring(id.outerStart,id.outerEnd), value), piece, defined);
}
else
value=findString(E,ignoreStats,defPrefix,id.var, piece, defined);
if(CMath.isMathExpression(value))
{
final String origValue = value;
final double val=CMath.parseMathExpression(value);
if(Math.round(val)==val)
value=""+Math.round(val);
else
value=""+val;
if((origValue.indexOf('?')>0) // random levels need to be chosen ONCE, esp when name is involved.
&&(missingMobVarCondition)
&&(defined != null))
defined.put(upperId,value);
}
fixed.put(id.var.toUpperCase(),value);
}
catch(final CMException e)
{
}
}
fixed.putAll(defined);
final boolean test= CMStrings.parseStringExpression(condition.toUpperCase(),fixed, true);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("MudPercolator","TEST "+piece.tag()+": "+condition+"="+test);
return test;
}
catch(final Exception e)
{
if(e instanceof PostProcessException)
throw (PostProcessException)e;
Log.errOut("Generate",e.getMessage()+": "+condition);
try {
CMStrings.parseStringExpression(condition,fixed, true);
}
catch(final Exception e1)
{
}
return false;
}
}
protected String getRequirementsDescription(final String values)
{
if(values==null)
return "";
if(values.equalsIgnoreCase("integer")||values.equalsIgnoreCase("int"))
return " as an integer or integer expression";
else
if(values.equalsIgnoreCase("double")||values.equalsIgnoreCase("#")||values.equalsIgnoreCase("number"))
return " as a number or numeric expression";
else
if(values.equalsIgnoreCase("string")||values.equalsIgnoreCase("$"))
return " as an open string";
else
if(values.trim().length()>0)
return " as one of the following values: "+values;
return "";
}
protected boolean checkRequirementsValue(final String validValue, final String value)
{
if(validValue==null)
return value != null;
if(validValue.equalsIgnoreCase("integer")||validValue.equalsIgnoreCase("int"))
return CMath.isMathExpression(value);
else
if(validValue.equalsIgnoreCase("double")||validValue.equalsIgnoreCase("#")||validValue.equalsIgnoreCase("number"))
return CMath.isMathExpression(value);
else
if(validValue.equalsIgnoreCase("string")||validValue.equalsIgnoreCase("$"))
return value.length()>0;
else
if(validValue.trim().length()>0)
return CMParms.containsIgnoreCase(CMParms.toStringArray(CMParms.parseSemicolons(validValue,true)),value);
return value.length()==0;
}
protected String cleanRequirementsValue(final String values, final String value)
{
if(values==null)
return value;
if(values.equalsIgnoreCase("integer")||values.equalsIgnoreCase("int"))
return Integer.toString(CMath.s_parseIntExpression(value));
else
if(values.equalsIgnoreCase("double")||values.equalsIgnoreCase("#")||values.equalsIgnoreCase("number"))
return Double.toString(CMath.s_parseMathExpression(value));
else
if(values.equalsIgnoreCase("string")||values.equalsIgnoreCase("$"))
return value;
else
if(values.trim().length()>0)
{
final String[] arrayStr=CMParms.toStringArray(CMParms.parseSemicolons(values,true));
int x=CMParms.indexOfIgnoreCase(arrayStr,value);
if(x<0)
x=0;
return arrayStr[x];
}
return value;
}
@Override
public Map<String,String> getUnfilledRequirements(final Map<String,Object> defined, final XMLTag piece)
{
String requirements = piece.getParmValue("REQUIRES");
final Map<String,String> set=new Hashtable<String,String>();
if(requirements==null)
return set;
requirements = requirements.trim();
final List<String> reqs = CMParms.parseCommas(requirements,true);
for(int r=0;r<reqs.size();r++)
{
String reqVariable=reqs.get(r);
if(reqVariable.startsWith("$"))
reqVariable=reqVariable.substring(1).trim();
String validValues=null;
final int x=reqVariable.indexOf('=');
if(x>=0)
{
validValues=reqVariable.substring(x+1).trim();
reqVariable=reqVariable.substring(0,x).trim();
}
if((!defined.containsKey(reqVariable.toUpperCase()))
||(!checkRequirementsValue(validValues, defined.get(reqVariable.toUpperCase()).toString())))
{
if(validValues==null)
set.put(reqVariable.toUpperCase(), "any");
else
if(validValues.equalsIgnoreCase("integer")||validValues.equalsIgnoreCase("int"))
set.put(reqVariable.toUpperCase(), "int");
else
if(validValues.equalsIgnoreCase("double")||validValues.equalsIgnoreCase("#")||validValues.equalsIgnoreCase("number"))
set.put(reqVariable.toUpperCase(), "double");
else
if(validValues.equalsIgnoreCase("string")||validValues.equalsIgnoreCase("$"))
set.put(reqVariable.toUpperCase(), "string");
else
if(validValues.trim().length()>0)
set.put(reqVariable.toUpperCase(), CMParms.toListString(CMParms.parseSemicolons(validValues,true)));
}
}
return set;
}
protected void checkRequirements(final Map<String,Object> defined, String requirements) throws CMException
{
if(requirements==null)
return;
requirements = requirements.trim();
final List<String> reqs = CMParms.parseCommas(requirements,true);
for(int r=0;r<reqs.size();r++)
{
String reqVariable=reqs.get(r);
if(reqVariable.startsWith("$"))
reqVariable=reqVariable.substring(1).trim();
String validValues=null;
final int x=reqVariable.indexOf('=');
if(x>=0)
{
validValues=reqVariable.substring(x+1).trim();
reqVariable=reqVariable.substring(0,x).trim();
}
if(!defined.containsKey(reqVariable.toUpperCase()))
throw new CMException("Required variable not defined: '"+reqVariable+"'. Please define this variable"+getRequirementsDescription(validValues)+".");
if(!checkRequirementsValue(validValues, defined.get(reqVariable.toUpperCase()).toString()))
throw new CMException("The required variable '"+reqVariable+"' is not properly defined. Please define this variable"+getRequirementsDescription(validValues)+".");
}
}
@Override
public void checkRequirements(final XMLTag piece, final Map<String,Object> defined) throws CMException
{
checkRequirements(defined,piece.getParmValue("REQUIRES"));
}
protected List<XMLTag> selectChoices(final Modifiable E, final String tagName, final List<String> ignoreStats, final String defPrefix, final List<XMLTag> choices, final XMLTag piece, final Map<String,Object> defined) throws CMException, PostProcessException
{
String selection = piece.getParmValue("SELECT");
if(selection == null)
return choices;
selection=selection.toUpperCase().trim();
List<XMLLibrary.XMLTag> selectedChoicesV=null;
if(selection.equals("NONE"))
selectedChoicesV= new Vector<XMLTag>();
else
if(selection.equals("ALL"))
selectedChoicesV=choices;
else
if((choices.size()==0)
&&(!selection.startsWith("ANY-0"))
&&(!selection.startsWith("FIRST-0"))
&&(!selection.startsWith("LAST-0"))
&&(!selection.startsWith("PICK-0"))
&&(!selection.startsWith("LIMIT-")))
{
throw new CMException("Can't make selection among NONE: on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
}
else
if(selection.equals("FIRST"))
selectedChoicesV= new XVector<XMLTag>(choices.get(0));
else
if(selection.startsWith("FIRST-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick first "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
for(int v=0;v<num;v++)
selectedChoicesV.add(choices.get(v));
}
else
if(selection.startsWith("LIMIT-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if(num<0)
throw new CMException("Can't pick limit "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
if(choices.size()<=num)
selectedChoicesV.addAll(choices);
else
while(selectedChoicesV.size()<num)
selectedChoicesV.add(choices.remove(CMLib.dice().roll(1, choices.size(), -1)));
}
else
if(selection.equals("LAST"))
selectedChoicesV=new XVector<XMLTag>(choices.get(choices.size()-1));
else
if(selection.startsWith("LAST-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick last "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
for(int v=choices.size()-num;v<choices.size();v++)
selectedChoicesV.add(choices.get(v));
}
else
if(selection.startsWith("PICK-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
final List<Integer> wV=new XArrayList<Integer>(choices.size(),true);
for(int c=0;c<cV.size();c++)
{
final XMLTag lilP=cV.get(c);
final String pickWeight=lilP.getParmValue("PICKWEIGHT");
final int weight;
if(pickWeight==null)
weight=0;
else
{
final String weightValue=strFilterNow(E,ignoreStats,defPrefix,pickWeight,piece, defined);
weight=CMath.s_parseIntExpression(weightValue);
}
if(weight < 0)
{
cV.remove(c);
c--;
}
else
{
wV.add(Integer.valueOf(weight));
}
}
for(int v=0;v<num;v++)
{
int total=0;
for(int c=0;c<cV.size();c++)
total += wV.get(c).intValue();
if(total==0)
{
if(cV.size()>0)
{
final int c=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(c));
cV.remove(c);
wV.remove(c);
}
}
else
{
int choice=CMLib.dice().roll(1,total,0);
int c=-1;
while(choice>0)
{
c++;
choice-=wV.get(c).intValue();
}
if((c>=0)&&(c<cV.size()))
{
selectedChoicesV.add(cV.get(c));
cV.remove(c);
wV.remove(c);
}
}
}
}
else
if(selection.equals("ANY"))
selectedChoicesV=new XVector<XMLTag>(choices.get(CMLib.dice().roll(1,choices.size(),-1)));
else
if(selection.startsWith("ANY-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick last "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
for(int v=0;v<num;v++)
{
final int x=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(x));
cV.remove(x);
}
}
else
if(selection.startsWith("REPEAT-"))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if(num<0)
throw new CMException("Can't pick last "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
for(int v=0;v<num;v++)
{
final int x=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(x));
}
}
else
if((selection.trim().length()>0)&&CMath.isMathExpression(selection))
{
final int num=CMath.parseIntExpression(strFilterNow(E,ignoreStats,defPrefix,selection.substring(selection.indexOf('-')+1),piece, defined));
if((num<0)||(num>choices.size()))
throw new CMException("Can't pick any "+num+" of "+choices.size()+" on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
selectedChoicesV=new Vector<XMLTag>();
final List<XMLLibrary.XMLTag> cV=new XArrayList<XMLLibrary.XMLTag>(choices);
for(int v=0;v<num;v++)
{
final int x=CMLib.dice().roll(1,cV.size(),-1);
selectedChoicesV.add(cV.get(x));
cV.remove(x);
}
}
else
throw new CMException("Illegal select type '"+selection+"' on piece '"+piece.tag()+"', Tag: "+tagName+", Data: "+CMParms.toKeyValueSlashListString(piece.parms())+":"+CMStrings.limit(piece.value(),100));
return selectedChoicesV;
}
protected String strFilterNow(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws CMException
{
try
{
return strFilter(E,ignoreStats,defPrefix,str,piece,defined);
}
catch(final PostProcessException pe)
{
throw new CMException("Post processing not permitted",pe);
}
}
private static enum SelectMQLState
{
STATE_SELECT0, // name
STATE_SELECT1, // as or from or ,
STATE_AS0, // as
STATE_AS1, // expect from or , ONLY
STATE_FROM0, // loc
STATE_FROM1, // paren
STATE_EXPECTWHEREOREND, // expect where
STATE_WHERE0, // object
STATE_WHERE1, // comparator
STATE_WHERE2, // object rhs
STATE_EXPECTCONNOREND, // expect connector or end of clause
STATE_WHEREEMBEDLEFT0, // got ( on left of comparator
STATE_WHEREEMBEDRIGHT0, // got ( on right of comparator
STATE_EXPECTNOTHING // end of where clause
}
/**
* Class for semi-parsed MQLClause, including method
* to do the parsig to fill out this object
*
* @author Bo Zimmerman
*
*/
private static class MQLClause
{
/**
* Connector descriptors for connecting mql where clauses together
* @author Bo Zimmerman
*
*/
private static enum WhereConnector { ENDCLAUSE, AND, OR }
/**
* Connector descriptors for connecting mql where clauses together
* @author Bo Zimmerman
*
*/
private static enum WhereComparator { EQ, NEQ, GT, LT, GTEQ, LTEQ, LIKE, IN, NOTLIKE, NOTIN }
/** An abstract Where Clause
* @author Bo Zimmerman
*
*/
private static class WhereComp
{
private String lhs = null;
private WhereComparator comp = null;
private String rhs = null;
}
private static class WhereClause
{
private WhereClause prev = null;
private WhereClause parent = null;
private WhereClause child = null;
private WhereComp lhs = null;
private WhereConnector conn = null;
private WhereClause next = null;
}
private enum AggregatorFunctions
{
COUNT,
MEDIAN,
MEAN,
UNIQUE,
FIRST,
ANY
}
private static class WhatBit extends Pair<String,String>
{
private WhatBit(final String what, final String as)
{
super(what,as);
}
private String what()
{
return first;
}
private String as()
{
return second;
}
@Override
public String toString()
{
if(first.equals(second))
return first;
return first+" as "+second;
}
}
private String mql = "";
private final List<WhatBit> what = new ArrayList<WhatBit>(1);
private String from = "";
private WhereClause wheres = null;
private boolean isTermProperlyEnded(final StringBuilder curr)
{
if(curr.length()<2)
return true;
if((curr.charAt(0)=='\"')
||(curr.charAt(0)=='\''))
{
final int endDex=curr.length()-1;
if(curr.charAt(endDex) != curr.charAt(0))
return false;
if((curr.length()>2)&&(curr.charAt(endDex-1)=='\\'))
return false;
}
return true;
}
/**
* parse the mql statement into this object
*
* @param str the original mql statement
* @param mqlbits mql statement, minus select: must be ALL UPPERCASE
* @throws CMException
*/
private void parseMQL(final String str, final String mqlbits) throws MQLException
{
this.mql=str;
final StringBuilder curr=new StringBuilder("");
int pdepth=0;
WhereClause wheres = new WhereClause();
this.wheres=wheres;
WhereComp wcomp = new WhereComp();
SelectMQLState state=SelectMQLState.STATE_SELECT0;
for(int i=0;i<=mqlbits.length();i++)
{
final char c=(i==mqlbits.length())?' ':mqlbits.charAt(i);
switch(state)
{
case STATE_SELECT0: // select state
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
// we just got a name symbol, so go to state 1 and expect AS or FROM or ,
what.add(new WhatBit(curr.toString(),curr.toString()));
state=SelectMQLState.STATE_SELECT1;
curr.setLength(0);
}
else
curr.append(c);
}
}
else
if(c==',')
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
what.add(new WhatBit(curr.toString(),curr.toString()));
curr.setLength(0);
}
else
curr.append(c);
}
else
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_SELECT1: // expect AS or FROM or ,
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(curr.toString().equals("FROM"))
{
curr.setLength(0);
state=SelectMQLState.STATE_FROM0;
}
else
if(curr.toString().equals("AS"))
{
curr.setLength(0);
state=SelectMQLState.STATE_AS0;
}
else
throw new MQLException("Unexpected select string in Malformed mql: "+str);
}
}
else
if(c==',')
{
if(curr.length()==0)
state=SelectMQLState.STATE_SELECT0;
else
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_AS0: // as name
{
if(Character.isWhitespace(c)
||(c==','))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
if(curr.toString().equals("FROM"))
throw new MQLException("Unexpected FROM in Malformed mql: "+str);
else
if(curr.toString().equals("AS"))
throw new MQLException("Unexpected AS in Malformed mql: "+str);
else
{
state=SelectMQLState.STATE_AS1; // expect from or , ONLY
what.get(what.size()-1).second = curr.toString();
curr.setLength(0);
}
}
else
curr.append(c);
}
else
if(c==',')
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_AS1: // expect FROM or , only
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(curr.toString().equals("FROM"))
{
curr.setLength(0);
state=SelectMQLState.STATE_FROM0;
}
else
throw new MQLException("Unexpected name string in Malformed mql: "+str);
}
}
else
if(c==',')
{
if(curr.length()==0)
state=SelectMQLState.STATE_SELECT0;
else
throw new MQLException("Unexpected , in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_FROM0: // from state
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
if(curr.toString().equals("WHERE"))
throw new MQLException("Unexpected WHERE in Malformed mql: "+str);
else
{
from=curr.toString();
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTWHEREOREND; // now expect where
}
}
else
curr.append(c);
}
}
else
if(c=='(')
{
if(curr.length()==0)
state=SelectMQLState.STATE_FROM1;
else
throw new MQLException("Unexpected ( in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_FROM1: // from () state
{
if(c=='(')
pdepth++;
else
if(c==')')
{
if(pdepth==0)
{
from=curr.toString();
state=SelectMQLState.STATE_EXPECTWHEREOREND; // expect where
curr.setLength(0);
}
else
pdepth--;
}
else
curr.append(c);
break;
}
case STATE_EXPECTWHEREOREND: // expect where clause
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(curr.toString().equals(";"))
{
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTNOTHING;
}
else
if(!curr.toString().equals("WHERE"))
throw new MQLException("Eexpected WHERE in Malformed mql: "+str);
else
{
curr.setLength(0);
state=SelectMQLState.STATE_WHERE0;
}
}
}
else
curr.append(c);
break;
}
case STATE_WHERE0: // initial where state
{
if(Character.isWhitespace(c)
||("<>!=".indexOf(c)>=0))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
wcomp=new WhereComp();
if((wheres.lhs!=null)
||(wheres.parent!=null))
{
final WhereClause newClause = new WhereClause();
newClause.prev=wheres;
wheres.next=newClause;
wheres=newClause;
}
wheres.lhs=wcomp;
wcomp.lhs = curr.toString();
curr.setLength(0);
if(!Character.isWhitespace(c))
curr.append(c);
state=SelectMQLState.STATE_WHERE1; // now expect comparator
}
else
curr.append(c);
}
}
else
if(c=='(')
{
if(curr.length()==0)
state=SelectMQLState.STATE_WHEREEMBEDLEFT0;
else
throw new MQLException("Unexpected ( in Malformed mql: "+str);
}
else
if(c==')')
throw new MQLException("Unexpected ) in Malformed mql: "+str);
else
curr.append(c);
break;
}
case STATE_WHEREEMBEDLEFT0:
{
if(c=='(')
{
if(curr.length()==0)
{
final WhereClause priorityClause = new WhereClause();
if((wheres.lhs!=null)
||(wheres.parent!=null)
||(wheres.conn!=null))
{
final WhereClause dummyClause = new WhereClause();
wheres.next=dummyClause;
dummyClause.prev=wheres;
wheres=dummyClause;
}
priorityClause.child=wheres;
wheres.parent=priorityClause;
wheres=priorityClause;
i--;
state=SelectMQLState.STATE_WHERE0; // expect lhs of a comp
}
else
pdepth++;
}
else
if(c==')')
{
if(pdepth==0)
{
wcomp=new WhereComp();
if((wheres.lhs!=null)
||(wheres.parent!=null)
||(wheres.conn!=null))
{
final WhereClause newClause = new WhereClause();
wheres.next=newClause;
newClause.prev=wheres;
wheres=newClause;
}
wheres.lhs=wcomp;
wcomp.lhs=curr.toString();
state=SelectMQLState.STATE_WHERE1; // expect connector or endofclause
curr.setLength(0);
}
else
pdepth--;
}
else
if(Character.isWhitespace(c) && (curr.length()==0))
{}
else
{
curr.append(c);
if((curr.length()<8)
&&(!"SELECT:".startsWith(curr.toString())))
{
final WhereClause priorityClause = new WhereClause();
if((wheres.lhs!=null)
||(wheres.parent!=null)
||(wheres.conn!=null))
{
final WhereClause dummyClause = new WhereClause();
wheres.next=dummyClause;
dummyClause.prev=wheres;
wheres=dummyClause;
}
priorityClause.child=wheres;
wheres.parent=priorityClause;
wheres=priorityClause;
i=mqlbits.lastIndexOf('(',i);
curr.setLength(0);
state=SelectMQLState.STATE_WHERE0; // expect lhs of a comp
}
}
break;
}
case STATE_WHERE1: // expect comparator
{
if(curr.length()==0)
{
if(!Character.isWhitespace(c))
curr.append(c);
}
else
{
boolean saveC = false;
boolean done=false;
if("<>!=".indexOf(c)>=0)
{
if("<>!=".indexOf(curr.charAt(0))>=0)
{
curr.append(c);
done=curr.length()>=2;
}
else
throw new MQLException("Unexpected '"+c+"' in Malformed mql: "+str);
}
else
if(!Character.isWhitespace(c))
{
if("<>!=".indexOf(curr.charAt(0))>=0)
{
saveC=true;
done=true;
}
else
curr.append(c);
}
else
done=true;
if(done)
{
final String fcurr=curr.toString();
if(fcurr.equals("="))
{
wcomp.comp=WhereComparator.EQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("!=")||fcurr.equals("<>"))
{
wcomp.comp=WhereComparator.NEQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals(">"))
{
wcomp.comp=WhereComparator.GT;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("<"))
{
wcomp.comp=WhereComparator.LT;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals(">=")||fcurr.equals("=>"))
{
wcomp.comp=WhereComparator.GTEQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("<=")||fcurr.equals("<="))
{
wcomp.comp=WhereComparator.LTEQ;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("IN"))
{
wcomp.comp=WhereComparator.IN;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("LIKE"))
{
wcomp.comp=WhereComparator.LIKE;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("NOTIN"))
{
wcomp.comp=WhereComparator.NOTIN;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
if(fcurr.equals("NOTLIKE"))
{
wcomp.comp=WhereComparator.NOTLIKE;
curr.setLength(0);
state=SelectMQLState.STATE_WHERE2; // now expect RHS
}
else
throw new MQLException("Unexpected '"+fcurr+"' in Malformed mql: "+str);
if(saveC)
curr.append(c);
}
}
break;
}
case STATE_WHERE2: // where rhs of clause
{
if(Character.isWhitespace(c))
{
if(curr.length()>0)
{
if(isTermProperlyEnded(curr))
{
wcomp.rhs=curr.toString();
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTCONNOREND;
}
else
curr.append(c);
}
}
else
if(c==')')
{
if(curr.length()==0)
throw new MQLException("Unexpected ): Malformed mql: "+str);
wcomp.rhs=curr.toString();
curr.setLength(0);
while(wheres.prev!=null)
wheres=wheres.prev;
if(wheres.child==null)
throw new MQLException("Unexpected ): Malformed mql: "+str);
wheres=wheres.child;
state=SelectMQLState.STATE_EXPECTCONNOREND;
}
else
if(c==';')
{
if(curr.length()==0)
throw new MQLException("Unexpected ; in Malformed mql: "+str);
else
{
wcomp.rhs=curr.toString();
curr.setLength(0);
state=SelectMQLState.STATE_EXPECTNOTHING;
}
}
else
if(c=='(')
{
if(curr.length()==0)
state=SelectMQLState.STATE_WHEREEMBEDRIGHT0;
else
throw new MQLException("Unexpected ( in Malformed mql: "+str);
}
else
curr.append(c);
break;
}
case STATE_WHEREEMBEDRIGHT0:
{
if(c=='(')
{
pdepth++;
}
else
if(c==')')
{
if(pdepth==0)
{
wcomp.rhs=curr.toString();
state=SelectMQLState.STATE_EXPECTCONNOREND; // expect connector or endofclause
curr.setLength(0);
}
else
pdepth--;
}
else
curr.append(c);
break;
}
case STATE_EXPECTCONNOREND: // expect connector or endofclause
{
if(c==';')
{
state=SelectMQLState.STATE_EXPECTNOTHING;
}
else
if(Character.isWhitespace(c) || (c=='('))
{
if(curr.length()>0)
{
if(curr.toString().equals("AND"))
{
wheres.conn = WhereConnector.AND;
state=SelectMQLState.STATE_WHERE0;
curr.setLength(0);
if(c=='(')
i--;
}
else
if(curr.toString().equals("OR"))
{
wheres.conn = WhereConnector.OR;
state=SelectMQLState.STATE_WHERE0;
curr.setLength(0);
if(c=='(')
i--;
}
else
throw new MQLException("Unexpected '"+curr.toString()+"': Malformed mql: "+str);
}
else
if(c=='(')
throw new MQLException("Unexpected ): Malformed mql: "+str);
}
else
if((c==')') && (curr.length()==0))
{
while(wheres.prev!=null)
wheres=wheres.prev;
if(wheres.child==null)
throw new MQLException("Unexpected ): Malformed mql: "+str);
wheres=wheres.child;
}
else
curr.append(c);
break;
}
default:
if(!Character.isWhitespace(c))
throw new MQLException("Unexpected '"+c+"': Malformed mql: "+str);
break;
}
}
if((state != SelectMQLState.STATE_EXPECTNOTHING)
&&(state != SelectMQLState.STATE_EXPECTWHEREOREND)
&&(state != SelectMQLState.STATE_EXPECTCONNOREND))
throw new MQLException("Unpected end of clause in state "+state.toString()+" in mql: "+str);
}
}
protected void doneWithMQLObject(final Object o)
{
if(o instanceof Physical)
{
final Physical P=(Physical)o;
if(!P.isSavable())
{
if((P instanceof DBIdentifiable)
&&(((DBIdentifiable)P).databaseID().equals("DELETE")))
P.destroy();
else
if((P instanceof Area)
&&(((Area)P).getAreaState()==Area.State.STOPPED))
P.destroy();
else
if((P instanceof Room)
&&(((Room)P).getArea().amDestroyed()))
P.destroy();
}
}
}
protected List<Object> parseMQLCMFile(final CMFile F, final String mql) throws MQLException
{
final List<Object> from=new LinkedList<Object>();
String str=F.text().toString().trim();
// normalize singletons
if(str.startsWith("<MOB>"))
str="<MOBS>"+str+"</MOB>";
else
if(str.startsWith("<ITEM>"))
str="<ITEMS>"+str+"</ITEMS>";
else
if(str.startsWith("<AREA>"))
str="<AREAS>"+str+"</AREAS>";
if(str.startsWith("<MOBS>"))
{
final List<MOB> mobList=new LinkedList<MOB>();
final String err = CMLib.coffeeMaker().addMOBsFromXML(str, mobList, null);
if((err!=null)&&(err.length()>0))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed mob parsing '"+err+"' in "+mql);
for(final MOB M : mobList)
{
CMLib.threads().deleteAllTicks(M);
M.setSavable(false);
M.setDatabaseID("DELETE");
}
from.addAll(mobList);
}
else
if(str.startsWith("<ITEMS>"))
{
final List<Item> itemList=new LinkedList<Item>();
final String err = CMLib.coffeeMaker().addItemsFromXML(str, itemList, null);
if((err!=null)&&(err.length()>0))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed item parsing '"+err+"' in "+mql);
for(final Item I : itemList)
{
CMLib.threads().deleteAllTicks(I);
I.setSavable(false);
I.setDatabaseID("DELETE");
}
from.addAll(itemList);
}
else
if(str.startsWith("<AREAS>"))
{
final List<Area> areaList=new LinkedList<Area>();
final List<List<XMLLibrary.XMLTag>> areas=new ArrayList<List<XMLLibrary.XMLTag>>();
String err=CMLib.coffeeMaker().fillAreasVectorFromXML(str,areas,null,null);
if((err!=null)&&(err.length()>0))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed area parsing '"+err+"' in "+mql);
for(final List<XMLLibrary.XMLTag> area : areas)
err=CMLib.coffeeMaker().unpackAreaFromXML(area, null, null, true, false);
for(final Area A : areaList)
{
CMLib.threads().deleteAllTicks(A);
A.setSavable(false);
A.setAreaState(State.STOPPED);
}
from.addAll(areaList);
}
else
if(str.startsWith("<AROOM>"))
{
final List<Room> roomList=new LinkedList<Room>();
final Area dumbArea=CMClass.getAreaType("StdArea");
CMLib.flags().setSavable(dumbArea, false);
final List<XMLLibrary.XMLTag> tags=CMLib.xml().parseAllXML(str);
final String err=CMLib.coffeeMaker().unpackRoomFromXML(dumbArea, tags, true, false);
if((err!=null)&&(err.length()>0)||(!dumbArea.getProperMap().hasMoreElements()))
throw new MQLException("CMFile "+F.getAbsolutePath()+" failed room parsing '"+err+"' in "+mql);
roomList.add(dumbArea.getProperMap().nextElement());
for(final Room R : roomList)
{
CMLib.threads().deleteAllTicks(R);
dumbArea.delProperRoom(R);
R.setSavable(false);
}
dumbArea.destroy();
from.addAll(roomList);
}
else
throw new MQLException("CMFile "+F.getAbsolutePath()+" not selectable from in "+mql);
return from;
}
protected List<Object> flattenMQLObjectList(final Collection<Object> from)
{
final List<Object> flat=new LinkedList<Object>();
for(final Object o1 : from)
{
if((o1 instanceof CMObject)
||(o1 instanceof String))
flat.add(o1);
else
if(o1 instanceof List)
{
@SuppressWarnings("unchecked")
final List<Object> nl = (List<Object>)o1;
flat.addAll(flattenMQLObjectList(nl));
}
else
if(o1 instanceof Map)
{
@SuppressWarnings("unchecked")
final Map<Object,Object> m=(Map<Object,Object>)o1;
flat.addAll(flattenMQLObjectList(m.values()));
}
else
flat.add(o1);
}
return flat;
}
protected List<Object> parseMQLFrom(final String fromClause, final String mql, final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Object> from=new LinkedList<Object>();
if(fromClause.startsWith("SELECT:"))
{
from.addAll(doMQLSelectObjs(E, ignoreStats, defPrefix, fromClause, piece, defined));
return from;
}
for(final String f : fromClause.split("\\\\"))
{
if(f.startsWith("/")
|| f.startsWith("::")
|| f.startsWith("//"))
{
final CMFile F=new CMFile(f,null);
if(!F.exists())
throw new MQLException("CMFile "+f+" not found in "+mql);
if(F.isDirectory())
{
for(final CMFile F2 : F.listFiles())
{
if(!F2.isDirectory())
from.addAll(this.parseMQLCMFile(F, mql));
}
}
else
from.addAll(this.parseMQLCMFile(F, mql));
}
else
if(f.equals("AREAS")
||((from.size()>0)&&(f.equals("AREA"))))
{
if(from.size()==0)
from.addAll(new XVector<Area>(CMLib.map().areas()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
final Area A;
if (o instanceof CMObject)
A=CMLib.map().areaLocation((CMObject)o);
else
A=null;
if(A==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(!from.contains(A))
from.add(A);
}
}
}
else
if(f.equals("AREA") && (from.size()==0))
{
final Area A=(E instanceof Environmental) ? CMLib.map().areaLocation(E) : null;
if(A==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(A))
from.add(A);
}
else
if(f.equals("ROOMS")
||((from.size()>0)&&(f.equals("ROOM"))))
{
if(from.size()==0)
from.addAll(new XVector<Room>(CMLib.map().rooms()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
final Room R;
if(o instanceof Area)
{
from.addAll(new XVector<Room>(((Area)o).getProperMap()));
continue;
}
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(!from.contains(R))
from.add(R);
}
}
}
else
if(f.equals("ROOM") && (from.size()==0))
{
final Room R=(E instanceof Environmental) ? CMLib.map().roomLocation((Environmental)E) : null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(R))
from.add(R);
}
else
if((f.equals("PLAYERS"))
||((from.size()>0)&&(f.equals("PLAYER"))))
{
if(from.size()==0)
{
final Enumeration<Session> sesss = new IteratorEnumeration<Session>(CMLib.sessions().allIterableAllHosts().iterator());
final Enumeration<MOB> m=new FilteredEnumeration<MOB>(new ConvertingEnumeration<Session, MOB>(sesss, sessionToMobConvereter), noMobFilter);
for(;m.hasMoreElements();)
from.add(m.nextElement());
}
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
final Enumeration<Session> sesss = new IteratorEnumeration<Session>(CMLib.sessions().allIterableAllHosts().iterator());
final Enumeration<MOB> m=new FilteredEnumeration<MOB>(new ConvertingEnumeration<Session, MOB>(sesss, sessionToMobConvereter), noMobFilter);
for(;m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(CMLib.map().areaLocation(M) == o)
from.add(M);
}
}
else
if(o instanceof Room)
{
for(final Enumeration<MOB> m=((Room)o).inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)
&&(M.isPlayer()))
from.add(M);
}
}
if(o instanceof MOB)
{
if(((MOB)o).isPlayer())
from.add(o);
}
else
if(o instanceof Item)
{
final Item I=(Item)o;
if((I.owner() instanceof MOB)
&&(((MOB)I.owner())).isPlayer())
from.add(I.owner());
}
else
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
}
}
}
else
if(f.equals("PLAYER") && (from.size()==0))
{
final MOB oE=(E instanceof MOB) ? (MOB)E : null;
if((oE==null)||(!oE.isPlayer()))
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("MOBS")
||((from.size()>0)&&(f.equals("MOB"))))
{
if(from.size()==0)
from.addAll(new XVector<MOB>(CMLib.map().worldMobs()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(!from.contains(M))
from.add(M);
}
}
}
}
else
if((o instanceof MOB)&&(f.equals("MOB")))
from.add(o);
else
{
final Room R;
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(!from.contains(M))
from.add(M);
}
}
}
}
}
}
else
if(f.equals("MOB") && (from.size()==0))
{
final Environmental oE=(E instanceof MOB) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("NPCS")
||((from.size()>0)&&(f.equals("NPC"))))
{
if(from.size()==0)
from.addAll(new XVector<MOB>(new FilteredEnumeration<MOB>(CMLib.map().worldMobs(),npcFilter)));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(npcFilter.passesFilter(M) && (!from.contains(M)))
from.add(M);
}
}
}
}
else
if((o instanceof MOB)
&&(f.equals("NPC"))
&&(npcFilter.passesFilter((MOB)o)))
from.add(o);
else
{
final Room R;
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
if(R.numInhabitants()>0)
{
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(npcFilter.passesFilter(M) && (!from.contains(M)))
from.add(M);
}
}
}
}
}
}
else
if(f.equals("NPC") && (from.size()==0))
{
final MOB oE=(E instanceof MOB) ? (MOB)E : null;
if((oE==null) || (oE.isPlayer()))
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("ITEMS")
||((from.size()>0)&&(f.equals("ITEM"))))
{
if(from.size()==0)
from.addAll(new XVector<Item>(CMLib.map().worldEveryItems()));
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
from.addAll(new XVector<Item>(r.nextElement().itemsRecursive()));
}
else
if((o instanceof Item)
&&(f.equals("ITEM")))
from.add(o);
else
{
final Room R;
if (o instanceof Environmental)
R=CMLib.map().roomLocation((Environmental)o);
else
R=null;
if(R==null)
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
else
from.addAll(new XVector<Item>(R.itemsRecursive()));
}
}
}
}
else
if(f.equals("ITEM") && (from.size()==0))
{
final Environmental oE=(E instanceof Item) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(!from.contains(oE))
from.add(oE);
}
else
if(f.equals("EQUIPMENT"))
{
if(from.size()==0)
{
final Environmental oE=(E instanceof MOB) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
{
for(final Enumeration<Item> i=((MOB)oE).items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
}
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<MOB> m=r.nextElement().inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
}
}
else
if(o instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)o).items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
else
if(o instanceof Room)
{
for(final Enumeration<MOB> m=((Room)o).inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.amBeingWornProperly()))
from.add(I);
}
}
}
else
if(o instanceof Item)
{
if(((Item)o).amBeingWornProperly())
from.add(o);
}
else
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
}
}
}
else
if(f.equals("OWNER"))
{
if(from.size()==0)
{
final Environmental oE=(E instanceof Item) ? (Environmental)E : null;
if(oE==null)
throw new MQLException("Unknown sub-from "+f+" on "+(""+E)+" in "+mql);
else
if(((Item)E).owner()!=null)
from.add(((Item)E).owner());
}
else
{
final List<Object> oldFrom=flattenMQLObjectList(from);
from.clear();
for(final Object o : oldFrom)
{
if(o instanceof Area)
{
for(final Enumeration<Room> r=((Area)o).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<MOB> m=r.nextElement().inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.owner()!=null)
&&(!from.contains(I.owner())))
from.add(I.owner());
}
}
}
}
else
if(o instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)o).items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.owner()!=null)
&&(!from.contains(I.owner())))
from.add(I.owner());
}
}
else
if(o instanceof Room)
{
for(final Enumeration<MOB> m=((Room)o).inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
for(final Enumeration<Item> i=M.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I!=null)
&&(I.owner()!=null)
&&(!from.contains(I.owner())))
from.add(I.owner());
}
}
}
else
if(o instanceof Item)
{
if(((Item)o).amBeingWornProperly())
from.add(o);
}
else
throw new MQLException("Unknown sub-from "+f+" on "+o.toString()+" in "+mql);
}
}
}
else
if(f.startsWith("$"))
{
final Object val = defined.get(f.substring(1));
if(val == null)
throw new MQLException("Unknown from clause selector '"+f+"' in "+mql);
if(val instanceof XMLTag)
{
final XMLTag tag=(XMLTag)val;
try
{
if(tag.tag().equalsIgnoreCase("STRING"))
from.add(findString(E,ignoreStats,defPrefix,"STRING",(XMLTag)val,defined));
else
{
final Object o =findObject(E,ignoreStats,defPrefix,"OBJECT",tag,defined);
if(o instanceof List)
{
@SuppressWarnings({ "unchecked" })
final List<Object> l=(List<Object>)o;
from.addAll(l);
}
else
from.add(o);
}
}
catch(final CMException e)
{
throw new MQLException(e.getMessage(),e);
}
}
else
from.add(val);
}
else
{
final Object asDefined = defined.get(f);
if(asDefined == null)
throw new MQLException("Unknown from clause selector '"+f+"' in "+mql);
if(asDefined instanceof List)
from.addAll((from));
else
from.add(asDefined);
}
}
return from;
}
protected Object getSimpleMQLValue(final String valueName, final Object from)
{
if(valueName.equals(".")||valueName.equals("*"))
return from;
if(from instanceof Map)
{
@SuppressWarnings({ "unchecked" })
final Map<String,Object> m=(Map<String,Object>)from;
if(m.containsKey(valueName))
return m.get(valueName);
for(final String key : m.keySet())
{
final Object o=m.get(key);
if(o instanceof CMObject)
return getSimpleMQLValue(valueName,o);
}
}
if(from instanceof List)
{
@SuppressWarnings("rawtypes")
final List l=(List)from;
if(l.size()>0)
return getSimpleMQLValue(valueName,l.get(0));
}
if(from instanceof MOB)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Item)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Room)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Area)
{
return CMLib.coffeeMaker().getAnyGenStat((Physical)from,valueName);
}
else
if(from instanceof Modifiable)
{
return ((Modifiable)from).getStat(valueName);
}
return null;
}
protected Object getFinalMQLValue(final String strpath, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
if(strpath.startsWith("SELECT:"))
{
if(from instanceof Modifiable)
return doMQLSelectObjs((Modifiable)from,ignoreStats,defPrefix,strpath,piece,defined);
else
return doMQLSelectObjs(E,ignoreStats,defPrefix,strpath,piece,defined);
}
Object finalO=null;
try
{
int index=0;
final String[] strs=CMStrings.replaceAll(strpath,"\\\\","\\").split("\\\\");
for(final String str : strs)
{
index++;
if(str.equals("*")||str.equals("."))
{
if(finalO==null)
finalO=from;
}
else
if(CMath.isNumber(str.trim()) || (str.trim().length()==0))
finalO=str.trim();
else
if(str.startsWith("\"")&&(str.endsWith("\""))&&(str.length()>1))
finalO=this.strFilter(E, ignoreStats, defPrefix, CMStrings.replaceAll(str.substring(1,str.length()-1),"\\\"","\""), piece, defined);
else
if(str.startsWith("'")&&(str.endsWith("'"))&&(str.length()>1))
finalO=this.strFilter(E, ignoreStats, defPrefix, CMStrings.replaceAll(str.substring(1,str.length()-1),"\\'","'"), piece, defined);
else
if(str.startsWith("`")&&(str.endsWith("`"))&&(str.length()>1))
finalO=this.strFilter(E, ignoreStats, defPrefix, CMStrings.replaceAll(str.substring(1,str.length()-1),"\\`","`"), piece, defined);
else
if(str.startsWith("COUNT"))
{
Object chkO=finalO;
if(chkO==null)
chkO=from;
if(chkO==null)
throw new MQLException("Can not count instances of null in '"+strpath+"'");
else
if(chkO instanceof List)
{
@SuppressWarnings("rawtypes")
final List l=(List)chkO;
chkO=""+l.size();
}
else
if((chkO instanceof String)
||(chkO instanceof Environmental))
{
if(index>1)
{
final StringBuilder whatBuilder=new StringBuilder("");
for(int i=0;i<index-1;i++)
whatBuilder.append(strs[i]).append("\\");
final String newWhat=whatBuilder.substring(0,whatBuilder.length()-1);
int count=0;
for(final Object o : allFrom)
{
if(o==from)
count++;
else
if(chkO.equals(getFinalMQLValue(newWhat, allFrom, o, E, ignoreStats, defPrefix, piece, defined)))
count++;
}
finalO=""+count;
}
else
finalO=""+allFrom.size();
}
else
finalO="1";
}
else
if(str.startsWith("$"))
{
Object val = defined.get(str.substring(1));
if(val instanceof XMLTag)
{
final XMLTag tag=(XMLTag)val;
if(tag.tag().equalsIgnoreCase("STRING"))
finalO=findString(E,ignoreStats,defPrefix,"STRING",(XMLTag)val,defined);
else
{
final Object o =findObject(E,ignoreStats,defPrefix,"OBJECT",tag,defined);
if(o instanceof Tickable)
CMLib.threads().deleteAllTicks((Tickable)o);
if(o instanceof List)
{
@SuppressWarnings("rawtypes")
final List l=(List)o;
for(final Object o2 : l)
{
if(o2 instanceof Tickable)
CMLib.threads().deleteAllTicks((Tickable)o2);
}
}
val=o;
}
}
if(val == null)
throw new MQLException("Unknown variable '$"+str+"' in str '"+str+"'",new CMException("$"+str));
finalO=val;
}
else
{
final Object fromO=(finalO==null)?from:finalO;
final Object newObj=getSimpleMQLValue(str,fromO);
if(newObj == null)
throw new MQLException("Unknown variable '"+str+"' on '"+fromO+"'",new CMException("$"+str));
finalO=newObj;
}
}
}
catch(final CMException e)
{
if(e instanceof MQLException)
throw (MQLException)e;
else
throw new MQLException("MQL failure on $"+strpath,e);
}
return finalO;
}
protected boolean doMQLComparison(final Object lhso, MQLClause.WhereComparator comp, final Object rhso, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final String lhstr=(lhso==null)?"":lhso.toString();
final String rhstr=(rhso==null)?"":rhso.toString();
if(lhso instanceof List)
{
if(rhso instanceof List)
{
@SuppressWarnings("rawtypes")
final List llhso=(List)lhso;
@SuppressWarnings("rawtypes")
final List lrhso=(List)rhso;
switch(comp)
{
case GT:
return llhso.size()>lrhso.size();
case LT:
return llhso.size()<lrhso.size();
case GTEQ:
if(llhso.size()>lrhso.size())
return true;
comp=MQLClause.WhereComparator.EQ;
break;
case LTEQ:
if(llhso.size()<lrhso.size())
return true;
comp=MQLClause.WhereComparator.EQ;
break;
default:
// see below;
break;
}
switch(comp)
{
case NEQ:
case EQ:
{
if(llhso.size()!=lrhso.size())
return (comp==MQLClause.WhereComparator.NEQ);
boolean allSame=true;
for(final Object o1 : llhso)
{
for(final Object o2 : lrhso)
allSame = allSame || doMQLComparison(o1, MQLClause.WhereComparator.EQ, o2, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
if(allSame)
return (comp==MQLClause.WhereComparator.EQ);
return (comp==MQLClause.WhereComparator.NEQ);
}
case LIKE:
case NOTLIKE:
{
if(llhso.size()!=lrhso.size())
return (comp==MQLClause.WhereComparator.NOTLIKE);
boolean allSame=true;
for(final Object o1 : llhso)
{
for(final Object o2 : lrhso)
allSame = allSame || doMQLComparison(o1, MQLClause.WhereComparator.LIKE, o2, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
if(allSame)
return (comp==MQLClause.WhereComparator.LIKE);
return (comp==MQLClause.WhereComparator.NOTLIKE);
}
case IN:
case NOTIN:
{
boolean allIn=true;
for(final Object o1 : llhso)
allIn = allIn || doMQLComparison(o1, MQLClause.WhereComparator.IN, lrhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
if(allIn)
return (comp==MQLClause.WhereComparator.IN);
return (comp==MQLClause.WhereComparator.NOTIN);
}
default:
// see above:
break;
}
}
else
{
@SuppressWarnings("unchecked")
final List<Object> l=(List<Object>)lhso;
boolean allIn=true;
for(final Object o1 : l)
allIn = allIn && doMQLComparison(o1, comp, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return allIn;
}
}
if((comp != MQLClause.WhereComparator.IN)
&&(comp != MQLClause.WhereComparator.NOTIN))
{
if(rhso instanceof List)
{
@SuppressWarnings("rawtypes")
final List rL=(List)rhso;
if(rL.size()>1)
{
return comp==MQLClause.WhereComparator.NEQ
|| comp==MQLClause.WhereComparator.NOTLIKE
|| comp==MQLClause.WhereComparator.LT
|| comp==MQLClause.WhereComparator.LTEQ;
}
return doMQLComparison(lhso, comp, rL.get(0), allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
if(lhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map mlhso=(Map)lhso;
boolean allSame=true;
for(final Object o1 : mlhso.keySet())
allSame = allSame && doMQLComparison(mlhso.get(o1), comp, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return allSame;
}
else
if(rhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map mrhso=(Map)rhso;
boolean allSame=true;
for(final Object o1 : mrhso.keySet())
allSame = allSame && doMQLComparison(lhso, comp, mrhso.get(o1), allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return allSame;
}
}
switch(comp)
{
case NEQ:
case EQ:
{
final boolean eq=(comp==MQLClause.WhereComparator.EQ);
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return (CMath.s_double(lhstr) == CMath.s_double(rhstr)) == eq;
if(lhso instanceof String)
{
if(rhso instanceof String)
return lhstr.equalsIgnoreCase(rhstr) == eq;
if(rhso instanceof Environmental)
return ((Environmental)rhso).Name().equalsIgnoreCase(lhstr) == eq;
else
return lhstr.equalsIgnoreCase(rhstr) == eq;
}
else
if(rhso instanceof String)
{
if(lhso instanceof Environmental)
return ((Environmental)lhso).Name().equalsIgnoreCase(rhstr) == eq;
else
return rhstr.equalsIgnoreCase(lhstr) == eq;
}
if(lhso instanceof Environmental)
{
if(rhso instanceof Environmental)
return ((Environmental)lhso).sameAs((Environmental)rhso) == eq;
throw new MQLException("'"+rhstr+"' can't be compared to '"+lhstr+"'");
}
else
if(rhso instanceof Environmental)
throw new MQLException("'"+rhstr+"' can't be compared to '"+lhstr+"'");
if((lhso != null)&&(rhso != null))
return (rhso.equals(rhso)) == eq;
else
return (lhso == rhso) == eq;
}
case GT:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) > CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) > 0;
return false; // objects can't be > than each other
case GTEQ:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) >= CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) >= 0;
return doMQLComparison(lhso, MQLClause.WhereComparator.EQ, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
case NOTIN:
case IN:
if(rhso instanceof List)
{
@SuppressWarnings("rawtypes")
final List lrhso=(List)rhso;
for(final Object o2 : lrhso)
{
if(doMQLComparison(lhso, MQLClause.WhereComparator.EQ, o2, allFrom, from,E,ignoreStats,defPrefix,piece,defined))
return comp==(MQLClause.WhereComparator.IN);
}
return comp==(MQLClause.WhereComparator.NOTIN);
}
if(rhso instanceof String)
{
if(lhso instanceof String)
return (rhstr.toUpperCase().indexOf(lhstr.toUpperCase()) >= 0) == (comp==MQLClause.WhereComparator.IN);
else
throw new MQLException("'"+lhstr+"' can't be in a string");
}
if(rhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map m=(Map)rhso;
if(m.containsKey(lhstr.toUpperCase()))
return (comp==MQLClause.WhereComparator.IN);
for(final Object key : m.keySet())
{
if(doMQLComparison(lhso, MQLClause.WhereComparator.EQ, m.get(key), allFrom, from,E,ignoreStats,defPrefix,piece,defined))
return comp==(MQLClause.WhereComparator.IN);
}
}
if(rhso instanceof Environmental)
{
return doMQLComparison(lhso, MQLClause.WhereComparator.EQ, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined)
== (comp==(MQLClause.WhereComparator.IN));
}
throw new MQLException("'"+rhstr+"' can't contain anything");
case NOTLIKE:
case LIKE:
if(!(rhso instanceof String))
throw new MQLException("Nothing can ever be LIKE '"+rhstr+"'");
if(lhso instanceof Environmental)
{
return CMLib.masking().maskCheck(rhstr, (Environmental)lhso, true)
== (comp==MQLClause.WhereComparator.LIKE);
}
if(lhso instanceof Map)
{
@SuppressWarnings("rawtypes")
final Map m=(Map)lhso;
Object o=m.get("CLASS");
if(!(o instanceof String))
throw new MQLException("'"+lhstr+"' can ever be LIKE anything.");
o=CMClass.getObjectOrPrototype((String)o);
if(o == null)
throw new MQLException("'"+lhstr+"' can ever be LIKE anything but nothing.");
if(!(o instanceof Modifiable))
throw new MQLException("'"+lhstr+"' can ever be LIKE anything modifiable.");
if(!(o instanceof Environmental))
throw new MQLException("'"+lhstr+"' can ever be LIKE anything envronmental.");
final Modifiable mo=(Modifiable)((Modifiable)o).newInstance();
for(final Object key : m.keySet())
{
if((key instanceof String)
&&(m.get(key) instanceof String))
mo.setStat((String)key, (String)m.get(key));
}
if(mo instanceof Environmental)
{
final boolean rv = CMLib.masking().maskCheck(rhstr, (Environmental)lhso, true)
== (comp==MQLClause.WhereComparator.LIKE);
((Environmental)mo).destroy();
return rv;
}
}
else
throw new MQLException("'"+lhstr+"' can ever be LIKE anything at all.");
break;
case LT:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) < CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) < 0;
return false; // objects can't be < than each other
case LTEQ:
if(CMath.isNumber(lhstr) && CMath.isNumber(rhstr))
return CMath.s_double(lhstr) <= CMath.s_double(rhstr);
if((lhstr instanceof String)||(rhstr instanceof String))
return lhstr.compareToIgnoreCase(rhstr) <= 0;
return doMQLComparison(lhso, MQLClause.WhereComparator.EQ, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
default:
break;
}
return true;
}
protected boolean doMQLComparison(final MQLClause.WhereComp comp, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final Object lhso=getFinalMQLValue(comp.lhs, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
final Object rhso=getFinalMQLValue(comp.rhs, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
return doMQLComparison(lhso, comp.comp, rhso, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
}
protected boolean doMQLWhereClauseFilter(final MQLClause.WhereClause whereClause, final List<Object> allFrom, final Object from,
final Modifiable E, final List<String> ignoreStats, final String defPrefix, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
MQLClause.WhereConnector lastConn=null;
MQLClause.WhereClause clause=whereClause;
boolean result=true;
while(clause != null)
{
boolean thisResult;
if(clause.parent != null)
{
if(clause.lhs != null)
throw new MQLException("Parent & lhs error ");
thisResult=doMQLWhereClauseFilter(clause.parent,allFrom,from,E,ignoreStats,defPrefix,piece,defined);
}
else
if(clause.lhs != null)
thisResult=doMQLComparison(clause.lhs, allFrom, from,E,ignoreStats,defPrefix,piece,defined);
else
if(clause.next != null)
{
if(clause.conn != null)
lastConn=clause.conn;
clause=clause.next;
continue;
}
else
return result;
if(lastConn != null)
{
switch(lastConn)
{
default:
case ENDCLAUSE:
case AND:
result=result&&thisResult;
break;
case OR:
result=result||thisResult;
break;
}
}
else
result=result&&thisResult;
if(clause.conn != null)
lastConn=clause.conn;
clause=clause.next;
}
return result;
}
protected List<Map<String,Object>> doSubObjSelect(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final MQLClause clause, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Map<String,Object>> results=new ArrayList<Map<String,Object>>();
// first estalish the from object
if(clause.from.length()==0)
throw new MQLException("No FROM clause in "+clause.mql);
// froms can have any environmental, or tags
final List<Object> froms=this.parseMQLFrom(clause.from, clause.mql, E, ignoreStats, defPrefix, piece, defined);
final MQLClause.AggregatorFunctions[] aggregates=new MQLClause.AggregatorFunctions[clause.what.size()];
boolean aggregate=false;
for(int i=0;i<clause.what.size();i++)
{
final String w=clause.what.get(i).what();
final int x=w.indexOf('\\');
if(x<0)
continue;
final MQLClause.AggregatorFunctions aggr=(MQLClause.AggregatorFunctions)CMath.s_valueOf(MQLClause.AggregatorFunctions.class, w.substring(0,x));
if(aggr != null)
{
clause.what.get(i).first=w.substring(x+1);
aggregates[i]=aggr;
aggregate=true;
}
}
for(final Object o : froms)
{
if(doMQLWhereClauseFilter(clause.wheres, froms, o,E,ignoreStats,defPrefix,piece,defined))
{
final Map<String,Object> m=new TreeMap<String,Object>();
for(final MQLClause.WhatBit bit : clause.what)
{
final Object o1 = this.getFinalMQLValue(bit.what(), froms, o, E, ignoreStats, defPrefix, piece, defined);
if(o1 instanceof Map)
{
@SuppressWarnings("unchecked")
final Map<String,Object> m2=(Map<String, Object>)o1;
m.putAll(m2);
}
else
m.put(bit.as(), o1);
}
results.add(m);
}
}
if(aggregate)
{
for(int i=0;i<aggregates.length;i++)
{
if(aggregates[i] == null)
continue;
final String whatName=clause.what.get(i).as();
switch(aggregates[i])
{
case COUNT:
{
final String sz=""+results.size();
results.clear();
final Map<String,Object> oneRow=new TreeMap<String,Object>();
results.add(oneRow);
oneRow.put(whatName, sz);
break;
}
case FIRST:
{
if(results.size()>0)
{
final Map<String,Object> first=results.get(0);
results.clear();
results.add(first);
}
break;
}
case ANY:
{
if(results.size()>0)
{
final Map<String,Object> any=results.get(CMLib.dice().roll(1, results.size(), -1));
results.clear();
results.add(any);
}
break;
}
case UNIQUE:
{
final List<Map<String,Object>> nonresults=new ArrayList<Map<String,Object>>(results.size());
nonresults.addAll(results);
results.clear();
final TreeSet<Object> done=new TreeSet<Object>(objComparator);
for(final Map<String,Object> r : results)
{
if(r.containsKey(whatName)
&&(r.get(whatName)!=null)
&&(!done.contains(r.get(whatName))))
{
done.add(r.get(whatName));
results.add(r);
}
}
break;
}
case MEDIAN:
{
final List<Object> allValues=new ArrayList<Object>(results.size());
for(final Map<String,Object> r : results)
{
if(r.containsKey(whatName)&&(r.get(whatName)!=null))
allValues.add(r.get(whatName));
}
Collections.sort(allValues,objComparator);
if(allValues.size()>0)
{
results.clear();
final Map<String,Object> oneRow=new TreeMap<String,Object>();
results.add(oneRow);
oneRow.put(clause.what.get(i).as(), allValues.get((int)Math.round(Math.floor(CMath.div(allValues.size(), 2)))));
}
break;
}
case MEAN:
{
double totalValue=0.0;
for(final Map<String,Object> r : results)
{
if(r.containsKey(whatName)&&(r.get(whatName)!=null))
totalValue += CMath.s_double(r.get(whatName).toString());
}
if(results.size()>0)
{
final String mean=""+(totalValue/results.size());
results.clear();
final Map<String,Object> oneRow=new TreeMap<String,Object>();
results.add(oneRow);
oneRow.put(clause.what.get(i).as(), mean);
}
break;
}
}
}
}
return results;
}
protected String convertMQLObjectToString(final Object o1)
{
if(o1 instanceof MOB)
return CMLib.coffeeMaker().getMobXML((MOB)o1).toString();
else
if(o1 instanceof Item)
return CMLib.coffeeMaker().getItemXML((Item)o1).toString();
else
if(o1 instanceof Ability)
return ((Ability)o1).ID();
else
if(o1 instanceof Room)
return CMLib.map().getExtendedRoomID((Room)o1);
else
if(o1 instanceof Area)
return ((Area)o1).Name();
else
if(o1 instanceof Behavior)
return ((Behavior)o1).ID();
else
if(o1 != null)
return o1.toString();
else
return "";
}
protected List<Map<String,String>> doSubSelectStr(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final MQLClause clause, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Map<String,String>> results=new ArrayList<Map<String,String>>();
final List<Map<String, Object>> objs=this.doSubObjSelect(E, ignoreStats, defPrefix, clause, piece, defined);
for(final Map<String,Object> o : objs)
{
final Map<String,String> n=new TreeMap<String,String>();
results.add(n);
for(final String key : o.keySet())
{
final Object o1=o.get(key);
n.put(key, this.convertMQLObjectToString(o1));
}
}
return results;
}
protected List<Map<String,String>> doMQLSelectStrs(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final int x=str.indexOf(':');
if(x<0)
throw new MQLException("Malformed mql: "+str);
final String mqlbits=str.substring(x+1).toUpperCase();
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("Starting MQL: "+mqlbits);
final MQLClause clause = new MQLClause();
clause.parseMQL(str, mqlbits);
return this.doSubSelectStr(E, ignoreStats, defPrefix, clause, piece, defined);
}
protected List<Map<String,Object>> doMQLSelectObjs(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final int x=str.indexOf(':');
if(x<0)
throw new MQLException("Malformed mql: "+str);
final String mqlbits=str.substring(x+1).toUpperCase();
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
Log.debugOut("Starting MQL: "+mqlbits);
final MQLClause clause = new MQLClause();
clause.parseMQL(str, mqlbits);
return this.doSubObjSelect(E, ignoreStats, defPrefix, clause, piece, defined);
}
protected String doMQLSelectString(final Modifiable E, final List<String> ignoreStats, final String defPrefix, final String str, final XMLTag piece, final Map<String,Object> defined) throws MQLException,PostProcessException
{
final List<Map<String,String>> res=doMQLSelectStrs(E,ignoreStats,defPrefix,str,piece,defined);
final StringBuilder finalStr = new StringBuilder("");
for(final Map<String,String> map : res)
{
for(final String key : map.keySet())
finalStr.append(map.get(key)).append(" ");
}
return finalStr.toString().trim();
}
@Override
public String doMQLSelectString(final Modifiable E, final String mql)
{
final Map<String,Object> defined=new TreeMap<String,Object>();
final XMLTag piece=CMLib.xml().createNewTag("tag", "value");
try
{
return doMQLSelectString(E,null,null,mql,piece,defined);
}
catch(final Exception e)
{
final ByteArrayOutputStream bout=new ByteArrayOutputStream();
final PrintStream pw=new PrintStream(bout);
e.printStackTrace(pw);
pw.flush();
return e.getMessage()+"\n\r"+bout.toString();
}
}
@Override
public List<Map<String,Object>> doMQLSelectObjects(final Modifiable E, final String mql) throws MQLException
{
final Map<String,Object> defined=new TreeMap<String,Object>();
final XMLTag piece=CMLib.xml().createNewTag("tag", "value");
try
{
return doMQLSelectObjs(E,null,null,mql,piece,defined);
}
catch(final PostProcessException e)
{
throw new MQLException("Cannot post-process MQL.", e);
}
}
protected String strFilter(Modifiable E, final List<String> ignoreStats, final String defPrefix, String str, final XMLTag piece, final Map<String,Object> defined) throws CMException,PostProcessException
{
List<Varidentifier> vars=parseVariables(str);
final boolean killArticles=str.toLowerCase().startsWith("(a(n))");
while(vars.size()>0)
{
final Varidentifier V=vars.remove(vars.size()-1);
Object val;
if(V.isMathExpression)
{
final String expression=strFilter(E,ignoreStats,defPrefix,V.var,piece, defined);
if(CMath.isMathExpression(expression))
{
if(expression.indexOf('.')>0)
val=""+CMath.parseMathExpression(expression);
else
val=""+CMath.parseLongExpression(expression);
}
else
throw new CMException("Invalid math expression '$"+expression+"' in str '"+str+"'");
}
else
if(V.var.toUpperCase().startsWith("SELECT:"))
{
val=doMQLSelectString(E,ignoreStats,defPrefix,V.var,piece, defined);
}
else
if(V.var.toUpperCase().startsWith("STAT:") && (E!=null))
{
final String[] parts=V.var.toUpperCase().split(":");
if(E instanceof Environmental)
{
Environmental E2=(Environmental)E;
for(int p=1;p<parts.length-1;p++)
{
final Room R=CMLib.map().roomLocation(E2);
Environmental E3;
if(parts[p].equals("ROOM"))
E3=CMLib.map().roomLocation(E2);
else
if(parts[p].equals("AREA"))
E3=CMLib.map().areaLocation(E2);
else
if(CMLib.directions().getDirectionCode(parts[p])>=0)
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
final int dir=CMLib.directions().getDirectionCode(parts[p]);
E3=R.getRoomInDir(dir);
}
else
if(parts[p].equals("ANYROOM"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
final List<Room> dirs=new ArrayList<Room>();
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
final Room R2=R.getRoomInDir(d);
if((R2!=null)
&&((R2.roomID().length()>0)
||((R.rawDoors()[d] instanceof GridLocale)
&&(R.rawDoors()[d].roomID().length()>0))))
dirs.add(R2);
}
if(dirs.size()==0)
throw new PostProcessException("No anyrooms on object "+E2.ID()+" ("+R.roomID()+"/"+R+") in variable '"+V.var+"' ");
E3=dirs.get(CMLib.dice().roll(1, dirs.size(), -1));
}
else
if(parts[p].equals("MOB"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
if((R.numInhabitants()==0)||((E2 instanceof MOB)&&(R.numInhabitants()==1)))
throw new PostProcessException("No mobs in room for "+E2.ID()+" in variable '"+V.var+"'");
E3=R.fetchInhabitant(CMLib.dice().roll(1, R.numInhabitants(), -1));
}
else
if(parts[p].equals("ITEM"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
if((R.numItems()==0)||((E2 instanceof Item)&&(R.numItems()==1)))
throw new PostProcessException("No items in room for "+E2.ID()+" in variable '"+V.var+"'");
E3=R.getItem(CMLib.dice().roll(1, R.numItems(), -1));
}
else
if(parts[p].equals("AREAGATE"))
{
if(R==null)
throw new PostProcessException("Unknown room on object "+E2.ID()+" in variable '"+V.var+"'");
final List<Room> dirs=new ArrayList<Room>();
for(int d=0;d<Directions.NUM_DIRECTIONS();d++)
{
final Room R2=R.getRoomInDir(d);
if((R2!=null) && (R2.roomID().length()>0) && (R.getArea()!=R2.getArea()))
dirs.add(R.getRoomInDir(d));
}
if(dirs.size()==0)
{
if(defined.get("ROOMTAG_GATEEXITROOM") instanceof Room)
dirs.add((Room)defined.get("ROOMTAG_GATEEXITROOM"));
if(dirs.size()==0)
throw new PostProcessException("No areagates on object "+E2.ID()+" in variable '"+V.var+"'");
}
E3=dirs.get(CMLib.dice().roll(1, dirs.size(), -1));
}
else
throw new PostProcessException("Unknown stat code '"+parts[p]+"' on object "+E2.ID()+" in variable '"+V.var+"'");
if(E3==null)
throw new PostProcessException("Unknown '"+parts[p]+"' on object "+E2.ID()+" in variable '"+V.var+"'");
else
E2=E3;
}
E=E2;
}
if (E.isStat(parts[parts.length-1]))
val=E.getStat(parts[parts.length-1]);
else
throw new CMException("Unknown stat code '"+parts[parts.length-1]+"' on object "+E+" in variable '"+V.var+"'");
}
else
val = defined.get(V.var.toUpperCase().trim());
if(val instanceof XMLTag)
{
val = findString(E,ignoreStats,defPrefix,"STRING",(XMLTag)val,defined);
}
if((val == null)&&(defPrefix!=null)&&(defPrefix.length()>0)&&(E!=null))
{
String preValue=V.var;
if(preValue.toUpperCase().startsWith(defPrefix.toUpperCase()))
{
preValue=preValue.toUpperCase().substring(defPrefix.length());
if((E.isStat(preValue))
&&((ignoreStats==null)||(!ignoreStats.contains(preValue.toUpperCase()))))
{
val=fillOutStatCode(E,ignoreStats,defPrefix,preValue,piece,defined, false);
XMLTag statPiece=piece;
while((val == null)
&&(statPiece.parent()!=null)
&&(!(defPrefix.startsWith(statPiece.tag())&&(!defPrefix.startsWith(statPiece.parent().tag())))))
{
statPiece=statPiece.parent();
val=fillOutStatCode(E,ignoreStats,defPrefix,preValue,statPiece,defined, false);
}
if((ignoreStats!=null)&&(val!=null))
ignoreStats.add(preValue.toUpperCase());
}
}
}
if(val == null)
throw new CMException("Unknown variable '$"+V.var+"' in str '"+str+"'",new CMException("$"+V.var));
if(V.toUpperCase)
val=val.toString().toUpperCase();
if(V.toLowerCase)
val=val.toString().toLowerCase();
if(V.toPlural)
val=CMLib.english().removeArticleLead(CMLib.english().makePlural(val.toString()));
if(V.toCapitalized)
val=CMStrings.capitalizeAndLower(val.toString());
if(V.toOneWord)
val=CMStrings.removePunctuation(val.toString().replace(' ', '_'));
if(killArticles)
val=CMLib.english().removeArticleLead(val.toString());
str=str.substring(0,V.outerStart)+val.toString()+str.substring(V.outerEnd);
if(vars.size()==0)
vars=parseVariables(str);
}
int x=str.toLowerCase().indexOf("(a(n))");
while((x>=0)&&(x<str.length()-8))
{
if((Character.isWhitespace(str.charAt(x+6)))
&&(Character.isLetter(str.charAt(x+7))))
{
if(CMStrings.isVowel(str.charAt(x+7)))
str=str.substring(0,x)+"an"+str.substring(x+6);
else
str=str.substring(0,x)+"a"+str.substring(x+6);
}
else
str=str.substring(0,x)+"a"+str.substring(x+6);
x=str.toLowerCase().indexOf("(a(n))");
}
return CMLib.xml().restoreAngleBrackets(str).replace('\'','`');
}
@Override
public String findString(final String tagName, final XMLTag piece, final Map<String, Object> defined) throws CMException
{
return findStringNow(null,null,null,tagName,piece,defined);
}
protected String findStringNow(final String tagName, final XMLTag piece, final Map<String, Object> defined) throws CMException
{
return findStringNow(null,null,null,tagName,piece,defined);
}
protected int makeNewLevel(final int level, final int oldMin, final int oldMax, final int newMin, final int newMax)
{
final double oldRange = oldMax-oldMin;
final double myOldRange = level - oldMin;
final double pctOfOldRange = myOldRange/oldRange;
final double newRange = newMax-newMin;
return newMin + (int)Math.round(pctOfOldRange * newRange);
}
@Override
public boolean relevelRoom(final Room room, final int oldMin, final int oldMax, final int newMin, final int newMax)
{
boolean changeMade=false;
try
{
room.toggleMobility(false);
CMLib.threads().suspendResumeRecurse(room, false, true);
if(CMLib.law().getLandTitle(room)!=null)
return false;
for(final Enumeration<Item> i=room.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if(I==null)
continue;
if((I instanceof Weapon)||(I instanceof Armor))
{
int newILevel=makeNewLevel(I.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newILevel <= 0)
newILevel = 1;
if(newILevel != I.phyStats().level())
{
final int levelDiff = newILevel - I.phyStats().level();
changeMade=true;
final int effectiveLevel =CMLib.itemBuilder().timsLevelCalculator(I) + levelDiff;
I.basePhyStats().setLevel(effectiveLevel);
I.phyStats().setLevel(effectiveLevel);
CMLib.itemBuilder().itemFix(I, effectiveLevel, null);
I.basePhyStats().setLevel(newILevel);
I.phyStats().setLevel(newILevel);
I.text();
}
}
}
for(final Enumeration<MOB> m=room.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)
&&(M.isMonster())
&&(M.getStartRoom()==room))
{
int newLevel=makeNewLevel(M.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newLevel <= 0)
newLevel = 1;
if(newLevel != M.phyStats().level())
{
changeMade=true;
final double spdDif = M.basePhyStats().speed() - CMLib.leveler().getLevelMOBSpeed(M);
final int armDif = M.basePhyStats().armor()-CMLib.leveler().getLevelMOBArmor(M);
final int dmgDif = M.basePhyStats().damage()-CMLib.leveler().getLevelMOBDamage(M);
final int attDif = M.basePhyStats().attackAdjustment()-CMLib.leveler().getLevelAttack(M);
M.basePhyStats().setLevel(newLevel);
M.phyStats().setLevel(newLevel);
CMLib.leveler().fillOutMOB(M,M.basePhyStats().level());
M.basePhyStats().setSpeed(M.basePhyStats().speed()+spdDif);
M.basePhyStats().setArmor(M.basePhyStats().armor()+armDif);
M.basePhyStats().setDamage(M.basePhyStats().damage()+dmgDif);
M.basePhyStats().setAttackAdjustment(M.basePhyStats().attackAdjustment()+attDif);
}
for(final Enumeration<Item> mi=M.items();mi.hasMoreElements();)
{
final Item mI=mi.nextElement();
if(mI!=null)
{
int newILevel=makeNewLevel(mI.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newILevel <= 0)
newILevel = 1;
if(newILevel != mI.phyStats().level())
{
final int levelDiff = newILevel - mI.phyStats().level();
changeMade=true;
final int effectiveLevel =CMLib.itemBuilder().timsLevelCalculator(mI) + levelDiff;
mI.basePhyStats().setLevel(effectiveLevel);
mI.phyStats().setLevel(effectiveLevel);
CMLib.itemBuilder().itemFix(mI, effectiveLevel, null);
mI.basePhyStats().setLevel(newILevel);
mI.phyStats().setLevel(newILevel);
mI.text();
}
}
}
final ShopKeeper SK=CMLib.coffeeShops().getShopKeeper(M);
if(SK!=null)
{
for(final Iterator<CoffeeShop.ShelfProduct> i=SK.getShop().getStoreShelves();i.hasNext();)
{
final CoffeeShop.ShelfProduct P=i.next();
final Environmental E2=P.product;
if((E2 instanceof Item)||(E2 instanceof MOB))
{
final Physical P2=(Physical)E2;
newLevel=makeNewLevel(P2.phyStats().level(),oldMin,oldMax,newMin,newMax);
if(newLevel <= 0)
newLevel = 1;
if(newLevel != P2.phyStats().level())
{
changeMade=true;
if(E2 instanceof Item)
{
final Item I2=(Item)E2;
final int levelDiff = newLevel - I2.phyStats().level();
final int effectiveLevel =CMLib.itemBuilder().timsLevelCalculator(I2) + levelDiff;
I2.basePhyStats().setLevel(effectiveLevel);
I2.phyStats().setLevel(effectiveLevel);
CMLib.itemBuilder().itemFix(I2, effectiveLevel, null);
}
P2.basePhyStats().setLevel(newLevel);
P2.phyStats().setLevel(newLevel);
if(E2 instanceof MOB)
CMLib.leveler().fillOutMOB((MOB)E2,P2.basePhyStats().level());
E2.text();
}
}
}
}
M.text();
M.recoverCharStats();
M.recoverMaxState();
M.recoverPhyStats();
M.recoverCharStats();
M.recoverMaxState();
M.recoverPhyStats();
M.resetToMaxState();
}
}
}
catch(final Exception e)
{
Log.errOut(e);
changeMade=false;
}
finally
{
room.recoverRoomStats();
CMLib.threads().suspendResumeRecurse(room, false, false);
room.toggleMobility(true);
room.recoverRoomStats();
}
return changeMade;
}
}
|
optimization in where clauses
git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@18532 0d6f1817-ed0e-0410-87c9-987e46238f29
|
com/planet_ink/coffee_mud/Libraries/MUDPercolator.java
|
optimization in where clauses
|
<ide><path>om/planet_ink/coffee_mud/Libraries/MUDPercolator.java
<ide> else
<ide> result=result&&thisResult;
<ide> if(clause.conn != null)
<add> {
<ide> lastConn=clause.conn;
<add> if(clause.next != null)
<add> {
<add> switch(lastConn)
<add> {
<add> case AND:
<add> if(!result)
<add> return false;
<add> break;
<add> case OR:
<add> if(result)
<add> return true;
<add> break;
<add> default:
<add> case ENDCLAUSE:
<add> break;
<add> }
<add> }
<add> }
<ide> clause=clause.next;
<ide> }
<ide> return result;
|
|
Java
|
apache-2.0
|
9a80346b0f57469be9e67f9de6096db4c3be42e0
| 0 |
JNOSQL/diana
|
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.document.query;
import org.hamcrest.Matchers;
import org.jnosql.artemis.CDIExtension;
import org.jnosql.artemis.Converters;
import org.jnosql.artemis.Param;
import org.jnosql.artemis.PreparedStatement;
import org.jnosql.artemis.Query;
import org.jnosql.artemis.Repository;
import org.jnosql.artemis.document.DocumentTemplate;
import org.jnosql.artemis.model.Person;
import org.jnosql.artemis.model.Vendor;
import org.jnosql.artemis.reflection.ClassMappings;
import org.jnosql.diana.api.Condition;
import org.jnosql.diana.api.TypeReference;
import org.jnosql.diana.api.Value;
import org.jnosql.diana.api.document.Document;
import org.jnosql.diana.api.document.DocumentCondition;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentQuery;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import javax.inject.Inject;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.jnosql.diana.api.Condition.AND;
import static org.jnosql.diana.api.Condition.BETWEEN;
import static org.jnosql.diana.api.Condition.EQUALS;
import static org.jnosql.diana.api.Condition.GREATER_THAN;
import static org.jnosql.diana.api.Condition.IN;
import static org.jnosql.diana.api.Condition.LESSER_EQUALS_THAN;
import static org.jnosql.diana.api.Condition.LESSER_THAN;
import static org.jnosql.diana.api.Condition.LIKE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(CDIExtension.class)
public class DocumentRepositoryProxyTest {
private DocumentTemplate template;
@Inject
private ClassMappings classMappings;
@Inject
private Converters converters;
private PersonRepository personRepository;
private VendorRepository vendorRepository;
@BeforeEach
public void setUp() {
this.template = Mockito.mock(DocumentTemplate.class);
DocumentRepositoryProxy personHandler = new DocumentRepositoryProxy(template,
classMappings, PersonRepository.class, converters);
DocumentRepositoryProxy vendorHandler = new DocumentRepositoryProxy(template,
classMappings, VendorRepository.class, converters);
when(template.insert(any(Person.class))).thenReturn(Person.builder().build());
when(template.insert(any(Person.class), any(Duration.class))).thenReturn(Person.builder().build());
when(template.update(any(Person.class))).thenReturn(Person.builder().build());
personRepository = (PersonRepository) Proxy.newProxyInstance(PersonRepository.class.getClassLoader(),
new Class[]{PersonRepository.class},
personHandler);
vendorRepository = (VendorRepository) Proxy.newProxyInstance(VendorRepository.class.getClassLoader(),
new Class[]{VendorRepository.class}, vendorHandler);
}
@Test
public void shouldSaveUsingInsertWhenDataDoesNotExist() {
when(template.find(Mockito.eq(Person.class), Mockito.eq(10L)))
.thenReturn(Optional.empty());
ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);
Person person = Person.builder().withName("Ada")
.withId(10L)
.withPhones(singletonList("123123"))
.build();
assertNotNull(personRepository.save(person));
verify(template).insert(captor.capture());
Person value = captor.getValue();
assertEquals(person, value);
}
@Test
public void shouldSaveUsingUpdateWhenDataExists() {
when(template.find(Mockito.eq(Person.class), Mockito.eq(10L)))
.thenReturn(Optional.of(Person.builder().build()));
ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);
Person person = Person.builder().withName("Ada")
.withId(10L)
.withPhones(singletonList("123123"))
.build();
assertNotNull(personRepository.save(person));
verify(template).update(captor.capture());
Person value = captor.getValue();
assertEquals(person, value);
}
@Test
public void shouldSaveIterable() {
when(personRepository.findById(10L)).thenReturn(Optional.empty());
when(template.singleResult(Mockito.any(DocumentQuery.class))).thenReturn(Optional.empty());
ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);
Person person = Person.builder().withName("Ada")
.withId(10L)
.withPhones(singletonList("123123"))
.build();
personRepository.save(singletonList(person));
verify(template).insert(captor.capture());
verify(template).insert(captor.capture());
Person personCapture = captor.getValue();
assertEquals(person, personCapture);
}
@Test
public void shouldFindByNameInstance() {
when(template.singleResult(Mockito.any(DocumentQuery.class))).thenReturn(Optional
.of(Person.builder().build()));
personRepository.findByName("name");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).singleResult(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(Condition.EQUALS, condition.getCondition());
assertEquals(Document.of("name", "name"), condition.getDocument());
assertNotNull(personRepository.findByName("name"));
when(template.singleResult(Mockito.any(DocumentQuery.class))).thenReturn(Optional
.empty());
assertNull(personRepository.findByName("name"));
}
@Test
public void shouldFindByNameANDAge() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
List<Person> persons = personRepository.findByNameAndAge("name", 20);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons, Matchers.contains(ada));
}
@Test
public void shouldFindByAgeANDName() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
Set<Person> persons = personRepository.findByAgeAndName(20, "name");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons, Matchers.contains(ada));
}
@Test
public void shouldFindByNameANDAgeOrderByName() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
Stream<Person> persons = personRepository.findByNameAndAgeOrderByName("name", 20);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons.collect(Collectors.toList()), Matchers.contains(ada));
}
@Test
public void shouldFindByNameANDAgeOrderByAge() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
Queue<Person> persons = personRepository.findByNameAndAgeOrderByAge("name", 20);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons, Matchers.contains(ada));
}
@Test
public void shouldDeleteByName() {
ArgumentCaptor<DocumentDeleteQuery> captor = ArgumentCaptor.forClass(DocumentDeleteQuery.class);
personRepository.deleteByName("Ada");
verify(template).delete(captor.capture());
DocumentDeleteQuery deleteQuery = captor.getValue();
DocumentCondition condition = deleteQuery.getCondition().get();
assertEquals("Person", deleteQuery.getDocumentCollection());
assertEquals(Condition.EQUALS, condition.getCondition());
assertEquals(Document.of("name", "Ada"), condition.getDocument());
}
@Test
public void shouldFindById() {
personRepository.findById(10L);
verify(template).find(Mockito.eq(Person.class), Mockito.eq(10L));
}
@Test
public void shouldFindByIds() {
when(template.find(Mockito.eq(Person.class), Mockito.any(Long.class)))
.thenReturn(Optional.of(Person.builder().build()));
personRepository.findById(singletonList(10L));
verify(template).find(Mockito.eq(Person.class), Mockito.eq(10L));
personRepository.findById(Arrays.asList(10L, 11L, 12L));
verify(template, times(4)).find(Mockito.eq(Person.class), any(Long.class));
}
@Test
public void shouldDeleteById() {
personRepository.deleteById(10L);
verify(template).delete(Person.class, 10L);
}
@Test
public void shouldDeleteByIds() {
personRepository.deleteById(singletonList(10L));
verify(template).delete(Person.class, 10L);
personRepository.deleteById(asList(1L, 2L, 3L));
verify(template, times(4)).delete(Mockito.eq(Person.class), any(Long.class));
}
@Test
public void shouldContainsById() {
when(template.find(Mockito.eq(Person.class), Mockito.any(Long.class)))
.thenReturn(Optional.of(Person.builder().build()));
assertTrue(personRepository.existsById(10L));
Mockito.verify(template).find(Mockito.eq(Person.class), Mockito.eq(10L));
when(template.find(Mockito.eq(Person.class), Mockito.any(Long.class)))
.thenReturn(Optional.empty());
assertFalse(personRepository.existsById(10L));
}
@Test
public void shouldFindAll() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
List<Person> persons = personRepository.findAll();
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
assertFalse(query.getCondition().isPresent());
assertEquals("Person", query.getDocumentCollection());
}
@Test
public void shouldReturnToString() {
assertNotNull(personRepository.toString());
}
@Test
public void shouldReturnHasCode() {
assertNotNull(personRepository.hashCode());
assertEquals(personRepository.hashCode(), personRepository.hashCode());
}
@Test
public void shouldReturnEquals() {
assertNotNull(personRepository.equals(personRepository));
}
@Test
public void shouldFindByNameAndAgeGreaterEqualThan() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByNameAndAgeGreaterThanEqual("Ada", 33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(AND, condition.getCondition());
List<DocumentCondition> conditions = condition.getDocument().get(new TypeReference<List<DocumentCondition>>() {
});
DocumentCondition columnCondition = conditions.get(0);
DocumentCondition columnCondition2 = conditions.get(1);
assertEquals(Condition.EQUALS, columnCondition.getCondition());
assertEquals("Ada", columnCondition.getDocument().get());
assertTrue(columnCondition.getDocument().getName().contains("name"));
assertEquals(Condition.GREATER_EQUALS_THAN, columnCondition2.getCondition());
assertEquals(33, columnCondition2.getDocument().get());
assertTrue(columnCondition2.getDocument().getName().contains("age"));
}
@Test
public void shouldFindByGreaterThan() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeGreaterThan(33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(GREATER_THAN, condition.getCondition());
assertEquals(Document.of("age", 33), condition.getDocument());
}
@Test
public void shouldFindByAgeLessThanEqual() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeLessThanEqual(33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(LESSER_EQUALS_THAN, condition.getCondition());
assertEquals(Document.of("age", 33), condition.getDocument());
}
@Test
public void shouldFindByAgeLessEqual() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeLessThan(33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(LESSER_THAN, condition.getCondition());
assertEquals(Document.of("age", 33), condition.getDocument());
}
@Test
public void shouldFindByAgeBetween() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeBetween(10, 15);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(BETWEEN, condition.getCondition());
List<Value> values = condition.getDocument().get(new TypeReference<List<Value>>() {
});
assertEquals(Arrays.asList(10, 15), values.stream().map(Value::get).collect(Collectors.toList()));
assertTrue(condition.getDocument().getName().contains("age"));
}
@Test
public void shouldFindByNameLike() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByNameLike("Ada");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(LIKE, condition.getCondition());
assertEquals(Document.of("name", "Ada"), condition.getDocument());
}
@Test
public void shouldFindByStringWhenFieldIsSet() {
Vendor vendor = new Vendor("vendor");
vendor.setPrefixes(Collections.singleton("prefix"));
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(vendor));
vendorRepository.findByPrefixes("prefix");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).singleResult(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("vendors", query.getDocumentCollection());
assertEquals(EQUALS, condition.getCondition());
assertEquals(Document.of("prefixes", "prefix"), condition.getDocument());
}
@Test
public void shouldFindByIn() {
Vendor vendor = new Vendor("vendor");
vendor.setPrefixes(Collections.singleton("prefix"));
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(vendor));
vendorRepository.findByPrefixesIn(singletonList("prefix"));
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).singleResult(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("vendors", query.getDocumentCollection());
assertEquals(IN, condition.getCondition());
assertEquals(Document.of("prefixes", "prefix"), condition.getDocument());
}
@Test
public void shouldConvertFieldToTheType() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAge("120");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(EQUALS, condition.getCondition());
assertEquals(Document.of("age", 120), condition.getDocument());
}
@Test
public void shouldExecuteJNoSQLQuery() {
personRepository.findByQuery();
verify(template).query("select * from Person");
}
@Test
public void shouldExecuteJNoSQLPrepare() {
PreparedStatement statement = Mockito.mock(PreparedStatement.class);
when(template.prepare(Mockito.anyString())).thenReturn(statement);
personRepository.findByQuery("Ada");
verify(statement).bind("id", "Ada");
}
interface PersonRepository extends Repository<Person, Long> {
List<Person> findAll();
Person findByName(String name);
List<Person> findByAge(String age);
void deleteByName(String name);
List<Person> findByNameAndAge(String name, Integer age);
Set<Person> findByAgeAndName(Integer age, String name);
Stream<Person> findByNameAndAgeOrderByName(String name, Integer age);
Queue<Person> findByNameAndAgeOrderByAge(String name, Integer age);
Set<Person> findByNameAndAgeGreaterThanEqual(String name, Integer age);
Set<Person> findByAgeGreaterThan(Integer age);
Set<Person> findByAgeLessThanEqual(Integer age);
Set<Person> findByAgeLessThan(Integer age);
Set<Person> findByAgeBetween(Integer ageA, Integer ageB);
Set<Person> findByNameLike(String name);
@Query("select * from Person")
Optional<Person> findByQuery();
@Query("select * from Person where id = @id")
Optional<Person> findByQuery(@Param("id") String id);
}
public interface VendorRepository extends Repository<Vendor, String> {
Vendor findByPrefixes(String prefix);
Vendor findByPrefixesIn(List<String> prefix);
}
}
|
mapping/artemis-document/src/test/java/org/jnosql/artemis/document/query/DocumentRepositoryProxyTest.java
|
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.document.query;
import org.hamcrest.Matchers;
import org.jnosql.artemis.CDIExtension;
import org.jnosql.artemis.Converters;
import org.jnosql.artemis.Param;
import org.jnosql.artemis.PreparedStatement;
import org.jnosql.artemis.Query;
import org.jnosql.artemis.Repository;
import org.jnosql.artemis.document.DocumentTemplate;
import org.jnosql.artemis.model.Person;
import org.jnosql.artemis.model.Vendor;
import org.jnosql.artemis.reflection.ClassMappings;
import org.jnosql.diana.api.Condition;
import org.jnosql.diana.api.TypeReference;
import org.jnosql.diana.api.Value;
import org.jnosql.diana.api.document.Document;
import org.jnosql.diana.api.document.DocumentCondition;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentQuery;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import javax.inject.Inject;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.jnosql.diana.api.Condition.AND;
import static org.jnosql.diana.api.Condition.BETWEEN;
import static org.jnosql.diana.api.Condition.EQUALS;
import static org.jnosql.diana.api.Condition.GREATER_THAN;
import static org.jnosql.diana.api.Condition.LESSER_EQUALS_THAN;
import static org.jnosql.diana.api.Condition.LESSER_THAN;
import static org.jnosql.diana.api.Condition.LIKE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(CDIExtension.class)
public class DocumentRepositoryProxyTest {
private DocumentTemplate template;
@Inject
private ClassMappings classMappings;
@Inject
private Converters converters;
private PersonRepository personRepository;
private VendorRepository vendorRepository;
@BeforeEach
public void setUp() {
this.template = Mockito.mock(DocumentTemplate.class);
DocumentRepositoryProxy personHandler = new DocumentRepositoryProxy(template,
classMappings, PersonRepository.class, converters);
DocumentRepositoryProxy vendorHandler = new DocumentRepositoryProxy(template,
classMappings, VendorRepository.class, converters);
when(template.insert(any(Person.class))).thenReturn(Person.builder().build());
when(template.insert(any(Person.class), any(Duration.class))).thenReturn(Person.builder().build());
when(template.update(any(Person.class))).thenReturn(Person.builder().build());
personRepository = (PersonRepository) Proxy.newProxyInstance(PersonRepository.class.getClassLoader(),
new Class[]{PersonRepository.class},
personHandler);
vendorRepository = (VendorRepository) Proxy.newProxyInstance(VendorRepository.class.getClassLoader(),
new Class[]{VendorRepository.class}, vendorHandler);
}
@Test
public void shouldSaveUsingInsertWhenDataDoesNotExist() {
when(template.find(Mockito.eq(Person.class), Mockito.eq(10L)))
.thenReturn(Optional.empty());
ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);
Person person = Person.builder().withName("Ada")
.withId(10L)
.withPhones(singletonList("123123"))
.build();
assertNotNull(personRepository.save(person));
verify(template).insert(captor.capture());
Person value = captor.getValue();
assertEquals(person, value);
}
@Test
public void shouldSaveUsingUpdateWhenDataExists() {
when(template.find(Mockito.eq(Person.class), Mockito.eq(10L)))
.thenReturn(Optional.of(Person.builder().build()));
ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);
Person person = Person.builder().withName("Ada")
.withId(10L)
.withPhones(singletonList("123123"))
.build();
assertNotNull(personRepository.save(person));
verify(template).update(captor.capture());
Person value = captor.getValue();
assertEquals(person, value);
}
@Test
public void shouldSaveIterable() {
when(personRepository.findById(10L)).thenReturn(Optional.empty());
when(template.singleResult(Mockito.any(DocumentQuery.class))).thenReturn(Optional.empty());
ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);
Person person = Person.builder().withName("Ada")
.withId(10L)
.withPhones(singletonList("123123"))
.build();
personRepository.save(singletonList(person));
verify(template).insert(captor.capture());
verify(template).insert(captor.capture());
Person personCapture = captor.getValue();
assertEquals(person, personCapture);
}
@Test
public void shouldFindByNameInstance() {
when(template.singleResult(Mockito.any(DocumentQuery.class))).thenReturn(Optional
.of(Person.builder().build()));
personRepository.findByName("name");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).singleResult(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(Condition.EQUALS, condition.getCondition());
assertEquals(Document.of("name", "name"), condition.getDocument());
assertNotNull(personRepository.findByName("name"));
when(template.singleResult(Mockito.any(DocumentQuery.class))).thenReturn(Optional
.empty());
assertNull(personRepository.findByName("name"));
}
@Test
public void shouldFindByNameANDAge() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
List<Person> persons = personRepository.findByNameAndAge("name", 20);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons, Matchers.contains(ada));
}
@Test
public void shouldFindByAgeANDName() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
Set<Person> persons = personRepository.findByAgeAndName(20, "name");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons, Matchers.contains(ada));
}
@Test
public void shouldFindByNameANDAgeOrderByName() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
Stream<Person> persons = personRepository.findByNameAndAgeOrderByName("name", 20);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons.collect(Collectors.toList()), Matchers.contains(ada));
}
@Test
public void shouldFindByNameANDAgeOrderByAge() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(Mockito.any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
Queue<Person> persons = personRepository.findByNameAndAgeOrderByAge("name", 20);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
assertThat(persons, Matchers.contains(ada));
}
@Test
public void shouldDeleteByName() {
ArgumentCaptor<DocumentDeleteQuery> captor = ArgumentCaptor.forClass(DocumentDeleteQuery.class);
personRepository.deleteByName("Ada");
verify(template).delete(captor.capture());
DocumentDeleteQuery deleteQuery = captor.getValue();
DocumentCondition condition = deleteQuery.getCondition().get();
assertEquals("Person", deleteQuery.getDocumentCollection());
assertEquals(Condition.EQUALS, condition.getCondition());
assertEquals(Document.of("name", "Ada"), condition.getDocument());
}
@Test
public void shouldFindById() {
personRepository.findById(10L);
verify(template).find(Mockito.eq(Person.class), Mockito.eq(10L));
}
@Test
public void shouldFindByIds() {
when(template.find(Mockito.eq(Person.class), Mockito.any(Long.class)))
.thenReturn(Optional.of(Person.builder().build()));
personRepository.findById(singletonList(10L));
verify(template).find(Mockito.eq(Person.class), Mockito.eq(10L));
personRepository.findById(Arrays.asList(10L, 11L, 12L));
verify(template, times(4)).find(Mockito.eq(Person.class), any(Long.class));
}
@Test
public void shouldDeleteById() {
personRepository.deleteById(10L);
verify(template).delete(Person.class, 10L);
}
@Test
public void shouldDeleteByIds() {
personRepository.deleteById(singletonList(10L));
verify(template).delete(Person.class, 10L);
personRepository.deleteById(asList(1L, 2L, 3L));
verify(template, times(4)).delete(Mockito.eq(Person.class), any(Long.class));
}
@Test
public void shouldContainsById() {
when(template.find(Mockito.eq(Person.class), Mockito.any(Long.class)))
.thenReturn(Optional.of(Person.builder().build()));
assertTrue(personRepository.existsById(10L));
Mockito.verify(template).find(Mockito.eq(Person.class), Mockito.eq(10L));
when(template.find(Mockito.eq(Person.class), Mockito.any(Long.class)))
.thenReturn(Optional.empty());
assertFalse(personRepository.existsById(10L));
}
@Test
public void shouldFindAll() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
List<Person> persons = personRepository.findAll();
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
assertFalse(query.getCondition().isPresent());
assertEquals("Person", query.getDocumentCollection());
}
@Test
public void shouldReturnToString() {
assertNotNull(personRepository.toString());
}
@Test
public void shouldReturnHasCode() {
assertNotNull(personRepository.hashCode());
assertEquals(personRepository.hashCode(), personRepository.hashCode());
}
@Test
public void shouldReturnEquals() {
assertNotNull(personRepository.equals(personRepository));
}
@Test
public void shouldFindByNameAndAgeGreaterEqualThan() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByNameAndAgeGreaterThanEqual("Ada", 33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(AND, condition.getCondition());
List<DocumentCondition> conditions = condition.getDocument().get(new TypeReference<List<DocumentCondition>>() {
});
DocumentCondition columnCondition = conditions.get(0);
DocumentCondition columnCondition2 = conditions.get(1);
assertEquals(Condition.EQUALS, columnCondition.getCondition());
assertEquals("Ada", columnCondition.getDocument().get());
assertTrue(columnCondition.getDocument().getName().contains("name"));
assertEquals(Condition.GREATER_EQUALS_THAN, columnCondition2.getCondition());
assertEquals(33, columnCondition2.getDocument().get());
assertTrue(columnCondition2.getDocument().getName().contains("age"));
}
@Test
public void shouldFindByGreaterThan() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeGreaterThan(33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(GREATER_THAN, condition.getCondition());
assertEquals(Document.of("age", 33), condition.getDocument());
}
@Test
public void shouldFindByAgeLessThanEqual() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeLessThanEqual(33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(LESSER_EQUALS_THAN, condition.getCondition());
assertEquals(Document.of("age", 33), condition.getDocument());
}
@Test
public void shouldFindByAgeLessEqual() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeLessThan(33);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(LESSER_THAN, condition.getCondition());
assertEquals(Document.of("age", 33), condition.getDocument());
}
@Test
public void shouldFindByAgeBetween() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAgeBetween(10, 15);
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(BETWEEN, condition.getCondition());
List<Value> values = condition.getDocument().get(new TypeReference<List<Value>>() {
});
assertEquals(Arrays.asList(10, 15), values.stream().map(Value::get).collect(Collectors.toList()));
assertTrue(condition.getDocument().getName().contains("age"));
}
@Test
public void shouldFindByNameLike() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByNameLike("Ada");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(LIKE, condition.getCondition());
assertEquals(Document.of("name", "Ada"), condition.getDocument());
}
@Test
public void shouldFindByStringWhenFieldIsSet() {
Vendor vendor = new Vendor("vendor");
vendor.setPrefixes(Collections.singleton("prefix"));
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(vendor));
vendorRepository.findByPrefixes("prefix");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).singleResult(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("vendors", query.getDocumentCollection());
assertEquals(EQUALS, condition.getCondition());
assertEquals(Document.of("prefixes", "prefix"), condition.getDocument());
}
@Test
public void shouldConvertFieldToTheType() {
Person ada = Person.builder()
.withAge(20).withName("Ada").build();
when(template.select(any(DocumentQuery.class)))
.thenReturn(singletonList(ada));
personRepository.findByAge("120");
ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(template).select(captor.capture());
DocumentQuery query = captor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(EQUALS, condition.getCondition());
assertEquals(Document.of("age", 120), condition.getDocument());
}
@Test
public void shouldExecuteJNoSQLQuery() {
personRepository.findByQuery();
verify(template).query("select * from Person");
}
@Test
public void shouldExecuteJNoSQLPrepare() {
PreparedStatement statement = Mockito.mock(PreparedStatement.class);
when(template.prepare(Mockito.anyString())).thenReturn(statement);
personRepository.findByQuery("Ada");
verify(statement).bind("id", "Ada");
}
interface PersonRepository extends Repository<Person, Long> {
List<Person> findAll();
Person findByName(String name);
List<Person> findByAge(String age);
void deleteByName(String name);
List<Person> findByNameAndAge(String name, Integer age);
Set<Person> findByAgeAndName(Integer age, String name);
Stream<Person> findByNameAndAgeOrderByName(String name, Integer age);
Queue<Person> findByNameAndAgeOrderByAge(String name, Integer age);
Set<Person> findByNameAndAgeGreaterThanEqual(String name, Integer age);
Set<Person> findByAgeGreaterThan(Integer age);
Set<Person> findByAgeLessThanEqual(Integer age);
Set<Person> findByAgeLessThan(Integer age);
Set<Person> findByAgeBetween(Integer ageA, Integer ageB);
Set<Person> findByNameLike(String name);
@Query("select * from Person")
Optional<Person> findByQuery();
@Query("select * from Person where id = @id")
Optional<Person> findByQuery(@Param("id") String id);
}
public interface VendorRepository extends Repository<Vendor, String> {
Vendor findByPrefixes(String prefix);
}
}
|
creates scenario to in
|
mapping/artemis-document/src/test/java/org/jnosql/artemis/document/query/DocumentRepositoryProxyTest.java
|
creates scenario to in
|
<ide><path>apping/artemis-document/src/test/java/org/jnosql/artemis/document/query/DocumentRepositoryProxyTest.java
<ide> import static org.jnosql.diana.api.Condition.BETWEEN;
<ide> import static org.jnosql.diana.api.Condition.EQUALS;
<ide> import static org.jnosql.diana.api.Condition.GREATER_THAN;
<add>import static org.jnosql.diana.api.Condition.IN;
<ide> import static org.jnosql.diana.api.Condition.LESSER_EQUALS_THAN;
<ide> import static org.jnosql.diana.api.Condition.LESSER_THAN;
<ide> import static org.jnosql.diana.api.Condition.LIKE;
<ide> }
<ide>
<ide> @Test
<add> public void shouldFindByIn() {
<add> Vendor vendor = new Vendor("vendor");
<add> vendor.setPrefixes(Collections.singleton("prefix"));
<add>
<add> when(template.select(any(DocumentQuery.class)))
<add> .thenReturn(singletonList(vendor));
<add>
<add> vendorRepository.findByPrefixesIn(singletonList("prefix"));
<add>
<add> ArgumentCaptor<DocumentQuery> captor = ArgumentCaptor.forClass(DocumentQuery.class);
<add> verify(template).singleResult(captor.capture());
<add> DocumentQuery query = captor.getValue();
<add> DocumentCondition condition = query.getCondition().get();
<add> assertEquals("vendors", query.getDocumentCollection());
<add> assertEquals(IN, condition.getCondition());
<add> assertEquals(Document.of("prefixes", "prefix"), condition.getDocument());
<add>
<add> }
<add>
<add>
<add> @Test
<ide> public void shouldConvertFieldToTheType() {
<ide> Person ada = Person.builder()
<ide> .withAge(20).withName("Ada").build();
<ide>
<ide> Vendor findByPrefixes(String prefix);
<ide>
<add> Vendor findByPrefixesIn(List<String> prefix);
<add>
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
e8e98ac9db9791477fb902b72ad1dd8a6ed9f944
| 0 |
google/mug,google/mug
|
/*****************************************************************************
* ------------------------------------------------------------------------- *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
*****************************************************************************/
package com.google.mu.util;
import static java.util.Objects.requireNonNull;
import java.io.Serializable;
import java.util.Optional;
import java.util.function.Function;
/**
* A substring inside a string, providing easy access to substrings around it
* ({@link #getBefore before}, {@link #getAfter after} or with the substring itself
* {@link #remove removed}, {@link #replaceWith replaced} etc.).
*
* <p>For example, to strip off the "http://" prefix from a uri string if existent: <pre>
* static String stripHttp(String uri) {
* return Substring.prefix("http://").removeFrom(uri);
* }
* </pre>
*
* To strip off either "http://" or "https://" prefix: <pre>
* static import com.google.mu.util.Substring.prefix;
*
* static String stripHttpOrHttps(String uri) {
* return prefix("http://").or(prefix("https://")).removeFrom(uri);
* }
* </pre>
*
* To strip off the suffix starting with a dash (-) character: <pre>
* static String stripDashSuffix(String str) {
* return Substring.from(last('-')).removeFrom(str);
* }
* </pre>
*
* To replace trailing "//" with "/": <pre>
* static String fixTrailingSlash(String str) {
* return Substring.suffix("//").replaceFrom(str, '/');
* }
* </pre>
*
* To extract the 'name' and 'value' from texts in the format of "name:value": <pre>
* String str = ...;
* Substring colon = Substring.first(':').in(str).orElseThrow(BadFormatException::new);
* String name = colon.getBefore();
* String value = colon.getAfter();
* </pre>
*
* @since 2.0
*/
public final class Substring {
/** {@code Pattern} that never matches any substring. */
public static final Pattern NONE = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
requireNonNull(s);
return null;
}
@Override public String toString() {
return "NONE";
}
};
/** {@code Pattern} that matches all strings entirely. */
public static final Pattern ALL = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
return new Substring(s, 0, s.length());
}
@Override public String toString() {
return "ALL";
}
};
/**
* {@code Pattern} that matches the empty substring at the beginning of the input string.
*
* @since 2.1
*/
public static final Pattern BEGINNING = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
return new Substring(s, 0, 0);
}
@Override public String toString() {
return "BEGINNING";
}
};
/**
* {@code Pattern} that matches the empty substring at the end of the input string.
*
* @since 2.1
*/
public static final Pattern END = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
return new Substring(s, s.length(), s.length());
}
@Override public String toString() {
return "END";
}
};
private final String context;
private final int startIndex;
private final int endIndex;
private Substring(String context, int startIndex, int endIndex) {
this.context = context;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
/** Returns a {@code Pattern} that matches strings starting with {@code prefix}. */
public static Pattern prefix(String prefix) {
requireNonNull(prefix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.startsWith(prefix) ? new Substring(str, 0, prefix.length()) : null;
}
};
}
/** Returns a {@code Pattern} that matches strings starting with {@code prefix}. */
public static Pattern prefix(char prefix) {
requireNonNull(prefix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.length() > 0 && str.charAt(0) == prefix ? new Substring(str, 0, 1) : null;
}
};
}
/** Returns a {@code Pattern} that matches strings ending with {@code suffix}. */
public static Pattern suffix(String suffix) {
requireNonNull(suffix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.endsWith(suffix)
? new Substring(str, str.length() - suffix.length(), str.length())
: null;
}
};
}
/** Returns a {@code Pattern} that matches strings ending with {@code suffix}. */
public static Pattern suffix(char suffix) {
requireNonNull(suffix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.length() > 0 && str.charAt(str.length() - 1) == suffix
? new Substring(str, str.length() - 1, str.length())
: null;
}
};
}
/** Returns a {@code Pattern} that matches the first occurrence of {@code c}. */
public static Pattern first(char c) {
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.indexOf(c), 1);
}
};
}
/** Returns a {@code Pattern} that matches the first occurrence of {@code snippet}. */
public static Pattern first(String snippet) {
requireNonNull(snippet);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.indexOf(snippet), snippet.length());
}
};
}
/**
* Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern}.
*
* <p>Unlike {@code str.replaceFirst(regexPattern, replacement)},
* <pre>regex(regexPattern).replaceFrom(str, replacement)</pre> treats the {@code replacement} as a literal
* string with no special handling of backslash (\) and dollar sign ($) characters.
*/
public static Pattern regex(java.util.regex.Pattern regexPattern) {
return regexGroup(regexPattern, 0);
}
/**
* Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern}.
*
* <p>Unlike {@code str.replaceFirst(regexPattern, replacement)},
* <pre>regex(regexPattern).replaceFrom(str, replacement)</pre> treats the {@code replacement} as a literal
* string with no special handling of backslash (\) and dollar sign ($) characters.
*
* <p>Because this method internally compiles {@code regexPattern}, it's more efficient to reuse the
* returned {@link Pattern} object than calling {@code regex(regexPattern)} repetitively.
*/
public static Pattern regex(String regexPattern) {
return regex(java.util.regex.Pattern.compile(regexPattern));
}
/**
* Returns a {@code Pattern} that matches capturing {@code group} of {@code regexPattern}.
*
* <p>The returned {@code Pattern} will throw {@link IndexOutOfBoundsException} when matched against
* strings without the target {@code group}.
*/
public static Pattern regexGroup(java.util.regex.Pattern regexPattern, int group) {
requireNonNull(regexPattern);
if (group < 0) throw new IllegalArgumentException("group cannot be negative: " + group);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
java.util.regex.Matcher matcher = regexPattern.matcher(str);
if (matcher.find()) {
return new Substring(str, matcher.start(group), matcher.end(group));
} else {
return null;
}
}
};
}
/**
* Returns a {@code Pattern} that matches capturing {@code group} of {@code regexPattern}.
*
* <p>Unlike {@code str.replaceFirst(regexPattern, replacement)},
* <pre>regexGroup(regexPattern, group).replaceFrom(str, replacement)</pre> treats the {@code replacement}
* as a literal string with no special handling of backslash (\) and dollar sign ($) characters.
*
* <p>Because this method internally compiles {@code regexPattern}, it's more efficient to reuse the
* returned {@link Pattern} object than calling {@code regexGroup(regexPattern, group)} repetitively.
*
* <p>The returned {@code Pattern} will throw {@link IndexOutOfBoundsException} when matched against
* strings without the target {@code group}.
*/
public static Pattern regexGroup(String regexPattern, int group) {
return regexGroup(java.util.regex.Pattern.compile(regexPattern), group);
}
/** Returns a {@code Pattern} that matches the last occurrence of {@code c}. */
public static Pattern last(char c) {
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.lastIndexOf(c), 1);
}
};
}
/** Returns a {@code Pattern} that matches the last occurrence of {@code snippet}. */
public static Pattern last(String snippet) {
requireNonNull(snippet);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.lastIndexOf(snippet), snippet.length());
}
};
}
/**
* Returns a {@code Pattern} that covers the substring before {@code delimiter}.
* For example: <pre>
* String startFromDoubleSlash = Substring.before(first("//")).removeFrom(uri);
* </pre>
*
* @since 2.1
*/
public static Pattern before(Pattern delimiter) {
return delimiter.map(Substring::preceding);
}
/**
* Returns a {@code Pattern} that covers the substring after {@code delimiter}.
* For example: <pre>
* String endWithPeriod = Substring.after(last(".")).removeFrom(line);
* </pre>
*
* @since 2.1
*/
public static Pattern after(Pattern delimiter) {
return delimiter.map(Substring::following);
}
/**
* Returns a {@code Pattern} that will match from {@code staringPoint} to the end of the input
* string. For example: <pre>
* String commentRemoved = Substring.from(first("//")).removeFrom(line);
* </pre>
*
* @since 2.1
*/
public static Pattern from(Pattern startingPoint) {
return startingPoint.map(Substring::toEnd);
}
/**
* Returns a {@code Pattern} that will match from the beginning of the input string up to
* {@code endingPoint} <em>inclusively</em>. For example: <pre>
* String schemeStripped = Substring.upTo(first("://")).removeFrom(uri);
* </pre>
*
* @since 2.1
*/
public static Pattern upTo(Pattern endingPoint) {
return endingPoint.map(Substring::fromBeginning);
}
/**
* Returns a {@code Pattern} that will match the substring between {@code open} and {@code close}.
* For example: <pre>
* String quoted = Substring.between(first('('), first(')'))
* .from(input)
* .orElseThrow(...);
* </pre>
*
* @since 2.1
*/
public static Pattern between(Pattern open, Pattern close) {
requireNonNull(open);
requireNonNull(close);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring left = open.match(str);
if (left == null) return null;
Substring right = close.match(str);
if (right == null) return null;
if (left.endIndex > right.startIndex) return null;
return new Substring(str, left.endIndex, right.startIndex);
}
};
}
/**
* Returns part before this substring.
*
* <p>{@link #getBefore} and {@link #getAfter} are almost always used together to split a string
* into two parts. Prefer using {@link #upTo} if you are trying to find a prefix ending
* with a pattern, like: <pre>
* String schemeStripped = Substring.upTo(first("://")).removeFrom(uri);
* </pre> or using {@link #from} to find a suffix starting with a pattern: <pre>
* String commentRemoved = Substring.from(first("//")).removeFrom(line);
* </pre>
*/
public String getBefore() {
return context.substring(0, startIndex);
}
/**
* Returns part after this substring.
*
* <p>{@link #getBefore} and {@link #getAfter} are almost always used together to split a string
* into two parts. Prefer using {@link Pattern#upTo} if you are trying to find a prefix ending
* with a pattern, like: <pre>
* String schemeStripped = Substring.upTo(first("://")).removeFrom(uri);
* </pre> or using {@link Pattern#from} to find a suffix starting with a pattern: <pre>
* String commentRemoved = Substring.from(first("//")).removeFrom(line);
* </pre>
*/
public String getAfter() {
return context.substring(endIndex);
}
/** Returns a new string with the substring removed. */
public String remove() {
if (endIndex == context.length()) {
return getBefore();
} else if (startIndex == 0) {
return getAfter();
} else {
return getBefore() + getAfter();
}
}
/** Returns a new string with {@code this} substring replaced by {@code replacement}. */
public String replaceWith(char replacement) {
return getBefore() + replacement + getAfter();
}
/** Returns a new string with {@code this} substring replaced by {@code replacement}. */
public String replaceWith(CharSequence replacement) {
requireNonNull(replacement);
return getBefore() + replacement + getAfter();
}
/** Returns the starting index of this substring in the containing string. */
public int getIndex() {
return startIndex;
}
/** Returns the length of this substring. */
public int length() {
return endIndex - startIndex;
}
/** Returns this substring. */
@Override public String toString() {
return context.substring(startIndex, endIndex);
}
@Override public int hashCode() {
return context.hashCode();
}
/** Two {@code Substring} instances are equal if they are the same sub sequences of equal strings. */
@Override public boolean equals(Object obj) {
if (obj instanceof Substring) {
Substring that = (Substring) obj;
return startIndex == that.startIndex && endIndex == that.endIndex
&& context.equals(that.context);
}
return false;
}
Substring subSequence(int begin, int end) {
if (begin < 0) {
throw new IndexOutOfBoundsException("Invalid index: " + begin);
}
if (begin > end) {
throw new IndexOutOfBoundsException("Invalid index: " + begin + " > " + end);
}
if (end > length()) {
throw new IndexOutOfBoundsException("Invalid index: " + end);
}
return new Substring(context, startIndex + begin, startIndex + end);
}
/** A substring pattern that can be matched against a string to find substrings. */
public static abstract class Pattern implements Serializable {
private static final long serialVersionUID = 1L;
/** Matches against {@code string} and returns null if not found. */
abstract Substring match(String string);
final Substring match(Substring substring) {
// TODO: should we match against substring directly without copying?
Substring innerMatch = match(substring.toString());
return innerMatch == null
? null
: substring.subSequence(innerMatch.startIndex, innerMatch.endIndex);
}
/** Finds the substring in {@code string} or returns {@code empty()} if not found. */
public final Optional<Substring> in(String string) {
return Optional.ofNullable(match(string));
}
/**
* Finds the substring in {@code string} or returns {@code empty()} if not found.
* {@code pattern.from(str)} is equivalent to {@code pattern.in(str).map(Object::toString)}.
*
* @since 2.1
*/
public final Optional<String> from(String string) {
return in(string).map(Object::toString);
}
/**
* Returns a new string with the substring matched by {@code this} removed. Returns {@code string} as is
* if a substring is not found.
*/
public final String removeFrom(String string) {
Substring substring = match(string);
return substring == null ? string : substring.remove();
}
/**
* Returns a new string with the substring matched by {@code this} replaced by {@code replacement}.
* Returns {@code string} as is if a substring is not found.
*/
public final String replaceFrom(String string, char replacement) {
Substring substring = match(string);
return substring == null ? string : substring.replaceWith(replacement);
}
/**
* Returns a new string with the substring matched by {@code this} replaced by {@code replacement}.
* Returns {@code string} as is if a substring is not found.
*/
public final String replaceFrom(String string, CharSequence replacement) {
requireNonNull(replacement);
Substring substring = match(string);
return substring == null ? string : substring.replaceWith(replacement);
}
/**
* Returns a {@code Pattern} that fall backs to using {@code that} if {@code this} fails to
* match.
*/
public final Pattern or(Pattern that) {
requireNonNull(that);
Pattern base = this;
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring substring = base.match(str);
return substring == null ? that.match(str) : substring;
}
};
}
/**
* Returns a modified {@code Pattern} of {@code this} scoped within the substring
* before {@code delimiter}. For example: {@code last('/').before(last('/'))} essentially
* finds the second last slash (/) character.
*
* @since 2.1
*/
public final Pattern before(Pattern delimiter) {
return within(Substring.before(delimiter));
}
/**
* Returns a modified {@code Pattern} of {@code this} scoped within the substring
* following {@code delimiter}. For example: {@code first('/').after(first('/'))} essentially
* finds the second slash (/) character.
*
* @since 2.1
*/
public final Pattern after(Pattern delimiter) {
return within(Substring.after(delimiter));
}
/**
* Returns a modified {@code Pattern} of {@code this} scoped between {@code open}
* and {@code close}. For example: <pre>
* first('=').between(first('('), first(')'))
* </pre> finds the equals (=) character between a pair of parenthesis.
*
* @since 2.1
*/
public final Pattern between(Pattern open, Pattern close) {
return within(Substring.between(open, close));
}
/**
* Returns a modified {@code Pattern} of {@code this} that matches within {@code scope}.
* For example: <pre>
* first('=').between(first('('), first(')'))}
* </pre> is equivalent to <pre>
* first('=').within(Substring.between(first('('), first(')')))
* </pre>
*
* @since 2.1
*/
public final Pattern within(Pattern scope) {
requireNonNull(scope);
Pattern inner = this;
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring outerMatch = scope.match(str);
return outerMatch == null ? null : inner.match(outerMatch);
}
};
}
private Pattern map(Mapper mapper) {
Pattern base = this;
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring substring = base.match(str);
return substring == null ? null : mapper.apply(substring);
}
};
}
/** @deprecated Use {@link Substring#before}. */
@Deprecated public final Pattern before() {
return Substring.before(this);
}
/** @deprecated Use {@link Substring#after}. */
@Deprecated public final Pattern after() {
return Substring.after(this);
}
/** @deprecated Use {@link Substring#upTo}. */
@Deprecated public final Pattern andBefore() {
return Substring.upTo(this);
}
/** @deprecated Use {@link Substring#from}. */
@Deprecated public final Pattern andAfter() {
return Substring.from(this);
}
private interface Mapper extends Function<Substring, Substring>, Serializable {}
}
private Substring preceding() {
return new Substring(context, 0, startIndex);
}
private Substring following() {
return new Substring(context, endIndex, context.length());
}
private Substring fromBeginning() {
return new Substring(context, 0, endIndex);
}
private Substring toEnd() {
return new Substring(context, startIndex, context.length());
}
private static Substring substringIfValidIndex(String str, int index, int length) {
return index >= 0 ? new Substring(str, index, index + length) : null;
}
}
|
core/src/main/java/com/google/mu/util/Substring.java
|
/*****************************************************************************
* ------------------------------------------------------------------------- *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
*****************************************************************************/
package com.google.mu.util;
import static java.util.Objects.requireNonNull;
import java.io.Serializable;
import java.util.Optional;
import java.util.function.Function;
/**
* A substring inside a string, providing easy access to substrings around it
* ({@link #getBefore before}, {@link #getAfter after} or with the substring itself
* {@link #remove removed}, {@link #replaceWith replaced} etc.).
*
* <p>For example, to strip off the "http://" prefix from a uri string if existent: <pre>
* static String stripHttp(String uri) {
* return Substring.prefix("http://").removeFrom(uri);
* }
* </pre>
*
* To strip off either "http://" or "https://" prefix: <pre>
* static import com.google.mu.util.Substring.prefix;
*
* static String stripHttpOrHttps(String uri) {
* return prefix("http://").or(prefix("https://")).removeFrom(uri);
* }
* </pre>
*
* To strip off the suffix starting with a dash (-) character: <pre>
* static String stripDashSuffix(String str) {
* return Substring.from(last('-')).removeFrom(str);
* }
* </pre>
*
* To replace trailing "//" with "/": <pre>
* static String fixTrailingSlash(String str) {
* return Substring.suffix("//").replaceFrom(str, '/');
* }
* </pre>
*
* To extract the 'name' and 'value' from texts in the format of "name:value": <pre>
* String str = ...;
* Substring colon = Substring.first(':').in(str).orElseThrow(BadFormatException::new);
* String name = colon.getBefore();
* String value = colon.getAfter();
* </pre>
*
* @since 2.0
*/
public final class Substring {
/** {@code Pattern} that never matches any substring. */
public static final Pattern NONE = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
requireNonNull(s);
return null;
}
@Override public String toString() {
return "NONE";
}
};
/** {@code Pattern} that matches all strings entirely. */
public static final Pattern ALL = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
return new Substring(s, 0, s.length());
}
@Override public String toString() {
return "ALL";
}
};
/**
* {@code Pattern} that matches the empty substring at the beginning of the input string.
*
* @since 2.1
*/
public static final Pattern BEGINNING = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
return new Substring(s, 0, 0);
}
@Override public String toString() {
return "BEGINNING";
}
};
/**
* {@code Pattern} that matches the empty substring at the end of the input string.
*
* @since 2.1
*/
public static final Pattern END = new Pattern() {
private static final long serialVersionUID = 1L;
@Override public Substring match(String s) {
return new Substring(s, s.length(), s.length());
}
@Override public String toString() {
return "END";
}
};
private final String context;
private final int startIndex;
private final int endIndex;
private Substring(String context, int startIndex, int endIndex) {
this.context = context;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
/** Returns a {@code Pattern} that matches strings starting with {@code prefix}. */
public static Pattern prefix(String prefix) {
requireNonNull(prefix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.startsWith(prefix) ? new Substring(str, 0, prefix.length()) : null;
}
};
}
/** Returns a {@code Pattern} that matches strings starting with {@code prefix}. */
public static Pattern prefix(char prefix) {
requireNonNull(prefix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.length() > 0 && str.charAt(0) == prefix ? new Substring(str, 0, 1) : null;
}
};
}
/** Returns a {@code Pattern} that matches strings ending with {@code suffix}. */
public static Pattern suffix(String suffix) {
requireNonNull(suffix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.endsWith(suffix)
? new Substring(str, str.length() - suffix.length(), str.length())
: null;
}
};
}
/** Returns a {@code Pattern} that matches strings ending with {@code suffix}. */
public static Pattern suffix(char suffix) {
requireNonNull(suffix);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return str.length() > 0 && str.charAt(str.length() - 1) == suffix
? new Substring(str, str.length() - 1, str.length())
: null;
}
};
}
/** Returns a {@code Pattern} that matches the first occurrence of {@code c}. */
public static Pattern first(char c) {
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.indexOf(c), 1);
}
};
}
/** Returns a {@code Pattern} that matches the first occurrence of {@code snippet}. */
public static Pattern first(String snippet) {
requireNonNull(snippet);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.indexOf(snippet), snippet.length());
}
};
}
/**
* Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern}.
*
* <p>Unlike {@code str.replaceFirst(regexPattern, replacement)},
* <pre>regex(regexPattern).replaceFrom(str, replacement)</pre> treats the {@code replacement} as a literal
* string with no special handling of backslash (\) and dollar sign ($) characters.
*/
public static Pattern regex(java.util.regex.Pattern regexPattern) {
return regexGroup(regexPattern, 0);
}
/**
* Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern}.
*
* <p>Unlike {@code str.replaceFirst(regexPattern, replacement)},
* <pre>regex(regexPattern).replaceFrom(str, replacement)</pre> treats the {@code replacement} as a literal
* string with no special handling of backslash (\) and dollar sign ($) characters.
*
* <p>Because this method internally compiles {@code regexPattern}, it's more efficient to reuse the
* returned {@link Pattern} object than calling {@code regex(regexPattern)} repetitively.
*/
public static Pattern regex(String regexPattern) {
return regex(java.util.regex.Pattern.compile(regexPattern));
}
/**
* Returns a {@code Pattern} that matches capturing {@code group} of {@code regexPattern}.
*
* <p>The returned {@code Pattern} will throw {@link IndexOutOfBoundsException} when matched against
* strings without the target {@code group}.
*/
public static Pattern regexGroup(java.util.regex.Pattern regexPattern, int group) {
requireNonNull(regexPattern);
if (group < 0) throw new IllegalArgumentException("group cannot be negative: " + group);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
java.util.regex.Matcher matcher = regexPattern.matcher(str);
if (matcher.find()) {
return new Substring(str, matcher.start(group), matcher.end(group));
} else {
return null;
}
}
};
}
/**
* Returns a {@code Pattern} that matches capturing {@code group} of {@code regexPattern}.
*
* <p>Unlike {@code str.replaceFirst(regexPattern, replacement)},
* <pre>regexGroup(regexPattern, group).replaceFrom(str, replacement)</pre> treats the {@code replacement}
* as a literal string with no special handling of backslash (\) and dollar sign ($) characters.
*
* <p>Because this method internally compiles {@code regexPattern}, it's more efficient to reuse the
* returned {@link Pattern} object than calling {@code regexGroup(regexPattern, group)} repetitively.
*
* <p>The returned {@code Pattern} will throw {@link IndexOutOfBoundsException} when matched against
* strings without the target {@code group}.
*/
public static Pattern regexGroup(String regexPattern, int group) {
return regexGroup(java.util.regex.Pattern.compile(regexPattern), group);
}
/** Returns a {@code Pattern} that matches the last occurrence of {@code c}. */
public static Pattern last(char c) {
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.lastIndexOf(c), 1);
}
};
}
/** Returns a {@code Pattern} that matches the last occurrence of {@code snippet}. */
public static Pattern last(String snippet) {
requireNonNull(snippet);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
return substringIfValidIndex(str, str.lastIndexOf(snippet), snippet.length());
}
};
}
/**
* Returns a {@code Pattern} that covers the substring before {@code delimiter}.
* For example: <pre>
* String startFromDoubleSlash = Substring.before(first("//")).removeFrom(uri);
* </pre>
*
* @since 2.1
*/
public static Pattern before(Pattern delimiter) {
return delimiter.map(Substring::preceding);
}
/**
* Returns a {@code Pattern} that covers the substring after {@code delimiter}.
* For example: <pre>
* String endWithPeriod = Substring.after(last(".")).removeFrom(line);
* </pre>
*
* @since 2.1
*/
public static Pattern after(Pattern delimiter) {
return delimiter.map(Substring::following);
}
/**
* Returns a {@code Pattern} that will match from {@code staringPoint} to the end of the input
* string. For example: <pre>
* String commentRemoved = Substring.from(first("//")).removeFrom(line);
* </pre>
*
* @since 2.1
*/
public static Pattern from(Pattern startingPoint) {
return startingPoint.map(Substring::toEnd);
}
/**
* Returns a {@code Pattern} that will match from the beginning of the input string up to
* {@code endingPoint} <em>inclusively</em>. For example: <pre>
* String schemeStripped = Substring.upTo(first("://")).removeFrom(uri);
* </pre>
*
* @since 2.1
*/
public static Pattern upTo(Pattern endingPoint) {
return endingPoint.map(Substring::fromBeginning);
}
/**
* Returns a {@code Pattern} that will match the substring between {@code open} and {@code close}.
* For example: <pre>
* String quoted = Substring.between(first('('), first(')'))
* .in(input)
* .orElseThrow(...)
* .toString();
* </pre>
*
* @since 2.1
*/
public static Pattern between(Pattern open, Pattern close) {
requireNonNull(open);
requireNonNull(close);
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring left = open.match(str);
if (left == null) return null;
Substring right = close.match(str);
if (right == null) return null;
if (left.endIndex > right.startIndex) return null;
return new Substring(str, left.endIndex, right.startIndex);
}
};
}
/**
* Returns part before this substring.
*
* <p>{@link #getBefore} and {@link #getAfter} are almost always used together to split a string
* into two parts. Prefer using {@link #upTo} if you are trying to find a prefix ending
* with a pattern, like: <pre>
* String schemeStripped = Substring.upTo(first("://")).removeFrom(uri);
* </pre> or using {@link #from} to find a suffix starting with a pattern: <pre>
* String commentRemoved = Substring.from(first("//")).removeFrom(line);
* </pre>
*/
public String getBefore() {
return context.substring(0, startIndex);
}
/**
* Returns part after this substring.
*
* <p>{@link #getBefore} and {@link #getAfter} are almost always used together to split a string
* into two parts. Prefer using {@link Pattern#upTo} if you are trying to find a prefix ending
* with a pattern, like: <pre>
* String schemeStripped = Substring.upTo(first("://")).removeFrom(uri);
* </pre> or using {@link Pattern#from} to find a suffix starting with a pattern: <pre>
* String commentRemoved = Substring.from(first("//")).removeFrom(line);
* </pre>
*/
public String getAfter() {
return context.substring(endIndex);
}
/** Returns a new string with the substring removed. */
public String remove() {
if (endIndex == context.length()) {
return getBefore();
} else if (startIndex == 0) {
return getAfter();
} else {
return getBefore() + getAfter();
}
}
/** Returns a new string with {@code this} substring replaced by {@code replacement}. */
public String replaceWith(char replacement) {
return getBefore() + replacement + getAfter();
}
/** Returns a new string with {@code this} substring replaced by {@code replacement}. */
public String replaceWith(CharSequence replacement) {
requireNonNull(replacement);
return getBefore() + replacement + getAfter();
}
/** Returns the starting index of this substring in the containing string. */
public int getIndex() {
return startIndex;
}
/** Returns the length of this substring. */
public int length() {
return endIndex - startIndex;
}
/** Returns this substring. */
@Override public String toString() {
return context.substring(startIndex, endIndex);
}
@Override public int hashCode() {
return context.hashCode();
}
/** Two {@code Substring} instances are equal if they are the same sub sequences of equal strings. */
@Override public boolean equals(Object obj) {
if (obj instanceof Substring) {
Substring that = (Substring) obj;
return startIndex == that.startIndex && endIndex == that.endIndex
&& context.equals(that.context);
}
return false;
}
Substring subSequence(int begin, int end) {
if (begin < 0) {
throw new IndexOutOfBoundsException("Invalid index: " + begin);
}
if (begin > end) {
throw new IndexOutOfBoundsException("Invalid index: " + begin + " > " + end);
}
if (end > length()) {
throw new IndexOutOfBoundsException("Invalid index: " + end);
}
return new Substring(context, startIndex + begin, startIndex + end);
}
/** A substring pattern that can be matched against a string to find substrings. */
public static abstract class Pattern implements Serializable {
private static final long serialVersionUID = 1L;
/** Matches against {@code string} and returns null if not found. */
abstract Substring match(String string);
final Substring match(Substring substring) {
// TODO: should we match against substring directly without copying?
Substring innerMatch = match(substring.toString());
return innerMatch == null
? null
: substring.subSequence(innerMatch.startIndex, innerMatch.endIndex);
}
/** Finds the substring in {@code string} or returns {@code empty()} if not found. */
public final Optional<Substring> in(String string) {
return Optional.ofNullable(match(string));
}
/**
* Finds the substring in {@code string} or returns {@code empty()} if not found.
* {@code pattern.from(str)} is equivalent to {@code pattern.in(str).map(Object::toString)}.
*
* @since 2.1
*/
public final Optional<String> from(String string) {
return in(string).map(Object::toString);
}
/**
* Returns a new string with the substring matched by {@code this} removed. Returns {@code string} as is
* if a substring is not found.
*/
public final String removeFrom(String string) {
Substring substring = match(string);
return substring == null ? string : substring.remove();
}
/**
* Returns a new string with the substring matched by {@code this} replaced by {@code replacement}.
* Returns {@code string} as is if a substring is not found.
*/
public final String replaceFrom(String string, char replacement) {
Substring substring = match(string);
return substring == null ? string : substring.replaceWith(replacement);
}
/**
* Returns a new string with the substring matched by {@code this} replaced by {@code replacement}.
* Returns {@code string} as is if a substring is not found.
*/
public final String replaceFrom(String string, CharSequence replacement) {
requireNonNull(replacement);
Substring substring = match(string);
return substring == null ? string : substring.replaceWith(replacement);
}
/**
* Returns a {@code Pattern} that fall backs to using {@code that} if {@code this} fails to
* match.
*/
public final Pattern or(Pattern that) {
requireNonNull(that);
Pattern base = this;
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring substring = base.match(str);
return substring == null ? that.match(str) : substring;
}
};
}
/**
* Returns a modified {@code Pattern} of {@code this} scoped within the substring
* before {@code delimiter}. For example: {@code last('/').before(last('/'))} essentially
* finds the second last slash (/) character.
*
* @since 2.1
*/
public final Pattern before(Pattern delimiter) {
return within(Substring.before(delimiter));
}
/**
* Returns a modified {@code Pattern} of {@code this} scoped within the substring
* following {@code delimiter}. For example: {@code first('/').after(first('/'))} essentially
* finds the second slash (/) character.
*
* @since 2.1
*/
public final Pattern after(Pattern delimiter) {
return within(Substring.after(delimiter));
}
/**
* Returns a modified {@code Pattern} of {@code this} scoped between {@code open}
* and {@code close}. For example: <pre>
* first('=').between(first('('), first(')'))
* </pre> finds the equals (=) character between a pair of parenthesis.
*
* @since 2.1
*/
public final Pattern between(Pattern open, Pattern close) {
return within(Substring.between(open, close));
}
/**
* Returns a modified {@code Pattern} of {@code this} that matches within {@code scope}.
* For example: <pre>
* first('=').between(first('('), first(')'))}
* </pre> is equivalent to <pre>
* first('=').within(Substring.between(first('('), first(')')))
* </pre>
*
* @since 2.1
*/
public final Pattern within(Pattern scope) {
requireNonNull(scope);
Pattern inner = this;
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring outerMatch = scope.match(str);
return outerMatch == null ? null : inner.match(outerMatch);
}
};
}
private Pattern map(Mapper mapper) {
Pattern base = this;
return new Pattern() {
private static final long serialVersionUID = 1L;
@Override Substring match(String str) {
Substring substring = base.match(str);
return substring == null ? null : mapper.apply(substring);
}
};
}
/** @deprecated Use {@link Substring#before}. */
@Deprecated public final Pattern before() {
return Substring.before(this);
}
/** @deprecated Use {@link Substring#after}. */
@Deprecated public final Pattern after() {
return Substring.after(this);
}
/** @deprecated Use {@link Substring#upTo}. */
@Deprecated public final Pattern andBefore() {
return Substring.upTo(this);
}
/** @deprecated Use {@link Substring#from}. */
@Deprecated public final Pattern andAfter() {
return Substring.from(this);
}
private interface Mapper extends Function<Substring, Substring>, Serializable {}
}
private Substring preceding() {
return new Substring(context, 0, startIndex);
}
private Substring following() {
return new Substring(context, endIndex, context.length());
}
private Substring fromBeginning() {
return new Substring(context, 0, endIndex);
}
private Substring toEnd() {
return new Substring(context, startIndex, context.length());
}
private static Substring substringIfValidIndex(String str, int index, int length) {
return index >= 0 ? new Substring(str, index, index + length) : null;
}
}
|
update between() javadoc to use from() instead of in() + toString()
|
core/src/main/java/com/google/mu/util/Substring.java
|
update between() javadoc to use from() instead of in() + toString()
|
<ide><path>ore/src/main/java/com/google/mu/util/Substring.java
<ide> * Returns a {@code Pattern} that will match the substring between {@code open} and {@code close}.
<ide> * For example: <pre>
<ide> * String quoted = Substring.between(first('('), first(')'))
<del> * .in(input)
<del> * .orElseThrow(...)
<del> * .toString();
<add> * .from(input)
<add> * .orElseThrow(...);
<ide> * </pre>
<ide> *
<ide> * @since 2.1
|
|
Java
|
apache-2.0
|
8a98b2b74d86449ba513c43cc86eb1751176aaa3
| 0 |
nobeans/incubator-groovy,nobeans/incubator-groovy,samanalysis/incubator-groovy,rabbitcount/incubator-groovy,alien11689/incubator-groovy,taoguan/incubator-groovy,upadhyayap/incubator-groovy,apache/incubator-groovy,gillius/incubator-groovy,bsideup/incubator-groovy,avafanasiev/groovy,sagarsane/incubator-groovy,i55ac/incubator-groovy,adjohnson916/groovy-core,groovy/groovy-core,rabbitcount/incubator-groovy,pledbrook/incubator-groovy,eginez/incubator-groovy,taoguan/incubator-groovy,PascalSchumacher/incubator-groovy,adjohnson916/incubator-groovy,avafanasiev/groovy,jwagenleitner/groovy,rlovtangen/groovy-core,groovy/groovy-core,fpavageau/groovy,apache/groovy,shils/groovy,paplorinc/incubator-groovy,nkhuyu/incubator-groovy,tkruse/incubator-groovy,dpolivaev/groovy,aaronzirbes/incubator-groovy,bsideup/incubator-groovy,sagarsane/groovy-core,ebourg/incubator-groovy,genqiang/incubator-groovy,ebourg/groovy-core,paulk-asert/incubator-groovy,aim-for-better/incubator-groovy,christoph-frick/groovy-core,bsideup/groovy-core,adjohnson916/incubator-groovy,adjohnson916/groovy-core,antoaravinth/incubator-groovy,rlovtangen/groovy-core,yukangguo/incubator-groovy,shils/groovy,aaronzirbes/incubator-groovy,eginez/incubator-groovy,dpolivaev/groovy,pickypg/incubator-groovy,upadhyayap/incubator-groovy,paplorinc/incubator-groovy,mariogarcia/groovy-core,adjohnson916/incubator-groovy,pickypg/incubator-groovy,christoph-frick/groovy-core,taoguan/incubator-groovy,armsargis/groovy,gillius/incubator-groovy,jwagenleitner/incubator-groovy,bsideup/groovy-core,sagarsane/incubator-groovy,jwagenleitner/groovy,yukangguo/incubator-groovy,avafanasiev/groovy,bsideup/groovy-core,guangying945/incubator-groovy,mariogarcia/groovy-core,tkruse/incubator-groovy,paulk-asert/groovy,armsargis/groovy,ChanJLee/incubator-groovy,shils/incubator-groovy,genqiang/incubator-groovy,shils/incubator-groovy,antoaravinth/incubator-groovy,rlovtangen/groovy-core,ChanJLee/incubator-groovy,samanalysis/incubator-groovy,alien11689/incubator-groovy,EPadronU/incubator-groovy,paulk-asert/groovy,fpavageau/groovy,alien11689/groovy-core,alien11689/groovy-core,russel/incubator-groovy,alien11689/incubator-groovy,i55ac/incubator-groovy,mariogarcia/groovy-core,adjohnson916/groovy-core,genqiang/incubator-groovy,shils/incubator-groovy,fpavageau/groovy,eginez/incubator-groovy,PascalSchumacher/incubator-groovy,i55ac/incubator-groovy,apache/groovy,EPadronU/incubator-groovy,paulk-asert/groovy,aaronzirbes/incubator-groovy,russel/groovy,christoph-frick/groovy-core,adjohnson916/groovy-core,russel/groovy,aim-for-better/incubator-groovy,taoguan/incubator-groovy,rabbitcount/incubator-groovy,upadhyayap/incubator-groovy,paplorinc/incubator-groovy,genqiang/incubator-groovy,kenzanmedia/incubator-groovy,eginez/incubator-groovy,gillius/incubator-groovy,pledbrook/incubator-groovy,PascalSchumacher/incubator-groovy,alien11689/groovy-core,russel/incubator-groovy,mariogarcia/groovy-core,sagarsane/groovy-core,nkhuyu/incubator-groovy,graemerocher/incubator-groovy,groovy/groovy-core,guangying945/incubator-groovy,paulk-asert/incubator-groovy,sagarsane/groovy-core,sagarsane/incubator-groovy,rlovtangen/groovy-core,armsargis/groovy,nkhuyu/incubator-groovy,groovy/groovy-core,upadhyayap/incubator-groovy,nobeans/incubator-groovy,aim-for-better/incubator-groovy,nobeans/incubator-groovy,graemerocher/incubator-groovy,kenzanmedia/incubator-groovy,guangying945/incubator-groovy,avafanasiev/groovy,dpolivaev/groovy,rabbitcount/incubator-groovy,nkhuyu/incubator-groovy,graemerocher/incubator-groovy,shils/incubator-groovy,ebourg/groovy-core,rlovtangen/groovy-core,paplorinc/incubator-groovy,jwagenleitner/groovy,bsideup/incubator-groovy,sagarsane/incubator-groovy,sagarsane/groovy-core,traneHead/groovy-core,ebourg/groovy-core,PascalSchumacher/incubator-groovy,shils/groovy,kidaa/incubator-groovy,yukangguo/incubator-groovy,apache/incubator-groovy,kenzanmedia/incubator-groovy,pledbrook/incubator-groovy,apache/groovy,alien11689/groovy-core,russel/groovy,PascalSchumacher/incubator-groovy,traneHead/groovy-core,ebourg/groovy-core,yukangguo/incubator-groovy,kenzanmedia/incubator-groovy,fpavageau/groovy,kidaa/incubator-groovy,alien11689/incubator-groovy,samanalysis/incubator-groovy,ebourg/incubator-groovy,traneHead/groovy-core,tkruse/incubator-groovy,mariogarcia/groovy-core,russel/incubator-groovy,jwagenleitner/groovy,jwagenleitner/incubator-groovy,graemerocher/incubator-groovy,aaronzirbes/incubator-groovy,ChanJLee/incubator-groovy,jwagenleitner/incubator-groovy,gillius/incubator-groovy,pickypg/incubator-groovy,alien11689/groovy-core,ebourg/groovy-core,kidaa/incubator-groovy,i55ac/incubator-groovy,adjohnson916/incubator-groovy,russel/incubator-groovy,christoph-frick/groovy-core,antoaravinth/incubator-groovy,pickypg/incubator-groovy,groovy/groovy-core,aim-for-better/incubator-groovy,adjohnson916/groovy-core,jwagenleitner/incubator-groovy,bsideup/groovy-core,apache/groovy,dpolivaev/groovy,apache/incubator-groovy,ebourg/incubator-groovy,christoph-frick/groovy-core,kidaa/incubator-groovy,paulk-asert/incubator-groovy,guangying945/incubator-groovy,pledbrook/incubator-groovy,paulk-asert/groovy,paulk-asert/incubator-groovy,apache/incubator-groovy,armsargis/groovy,tkruse/incubator-groovy,paulk-asert/incubator-groovy,EPadronU/incubator-groovy,samanalysis/incubator-groovy,antoaravinth/incubator-groovy,ChanJLee/incubator-groovy,EPadronU/incubator-groovy,bsideup/incubator-groovy,traneHead/groovy-core,shils/groovy,sagarsane/groovy-core,russel/groovy,ebourg/incubator-groovy
|
/*
* Copyright 2003-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 groovy.text;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import groovy.lang.Writable;
import groovy.util.IndentPrinter;
import groovy.util.Node;
import groovy.util.XmlNodePrinter;
import groovy.util.XmlParser;
import groovy.xml.QName;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.xml.sax.SAXException;
/**
* Template engine for xml data input.
*
* @author Christian Stein
* @author Paul King
*/
public class XmlTemplateEngine extends TemplateEngine {
private static class GspPrinter extends XmlNodePrinter {
public GspPrinter(PrintWriter out, String indent) {
this(new IndentPrinter(out, indent));
}
public GspPrinter(IndentPrinter out) {
super(out, "\\\"");
setQuote("'");
}
protected void printGroovyTag(String tag, String text) {
if (tag.equals("scriptlet")) {
out.print(text);
out.print("\n");
return;
}
if (tag.equals("expression")) {
printLineBegin();
out.print("${");
out.print(text);
out.print("}");
printLineEnd();
return;
}
throw new RuntimeException("Unsupported 'gsp:' tag named \"" + tag + "\".");
}
protected void printSimpleItem(Object value) {
this.printLineBegin();
out.print(escapeSpecialChars(InvokerHelper.toString(value)));
printLineEnd();
}
private String escapeSpecialChars(String s) {
s = s.replaceAll("\"", """);
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll("'", "'");
return s;
}
protected void printLineBegin() {
out.print("out.print(\"");
out.printIndent();
}
protected void printLineEnd(String comment) {
out.print("\\n\");");
if (comment != null) {
out.print(" // ");
out.print(comment);
}
out.print("\n");
}
protected boolean printSpecialNode(Node node) {
Object name = node.name();
if (name != null && name instanceof QName) {
QName qn = (QName) name;
if (qn.getPrefix().equals("gsp")) {
String s = qn.getLocalPart();
if (s.length() == 0) {
throw new RuntimeException("No local part after 'gsp:' given in node " + node);
}
printGroovyTag(s, node.text());
return true;
}
}
return false;
}
}
private static class XmlTemplate implements Template {
private final Script script;
public XmlTemplate(Script script) {
this.script = script;
}
public Writable make() {
return make(new HashMap());
}
public Writable make(Map map) {
if (map == null) {
throw new IllegalArgumentException("map must not be null");
}
return new XmlWritable(script, new Binding(map));
}
}
private static class XmlWritable implements Writable {
private final Binding binding;
private final Script script;
private WeakReference result;
public XmlWritable(Script script, Binding binding) {
this.script = script;
this.binding = binding;
this.result = new WeakReference(null);
}
public Writer writeTo(Writer out) {
Script scriptObject = InvokerHelper.createScript(script.getClass(), binding);
PrintWriter pw = new PrintWriter(out);
scriptObject.setProperty("out", pw);
scriptObject.run();
pw.flush();
return out;
}
public String toString() {
if (result.get() != null) {
return result.get().toString();
}
String string = writeTo(new StringWriter(1024)).toString();
result = new WeakReference(string);
return string;
}
}
public static final String DEFAULT_INDENTATION = " ";
private final GroovyShell groovyShell;
private final XmlParser xmlParser;
private String indentation;
public XmlTemplateEngine() throws SAXException, ParserConfigurationException {
this(DEFAULT_INDENTATION, false);
}
public XmlTemplateEngine(String indentation, boolean validating) throws SAXException, ParserConfigurationException {
this(new XmlParser(validating, true), new GroovyShell());
setIndentation(indentation);
}
public XmlTemplateEngine(XmlParser xmlParser, ClassLoader parentLoader) {
this(xmlParser, new GroovyShell(parentLoader));
}
public XmlTemplateEngine(XmlParser xmlParser, GroovyShell groovyShell) {
this.groovyShell = groovyShell;
this.xmlParser = xmlParser;
setIndentation(DEFAULT_INDENTATION);
}
public Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException {
Node root = null;
try {
root = xmlParser.parse(reader);
} catch (SAXException e) {
throw new RuntimeException("Parsing XML source failed.", e);
}
if (root == null) {
throw new IOException("Parsing XML source failed: root node is null.");
}
StringWriter writer = new StringWriter(1024);
writer.write("/* Generated by XmlTemplateEngine */\n");
new GspPrinter(new PrintWriter(writer), indentation).print(root);
Script script = groovyShell.parse(writer.toString());
return new XmlTemplate(script);
}
public String getIndentation() {
return indentation;
}
public void setIndentation(String indentation) {
if (indentation == null) {
indentation = DEFAULT_INDENTATION;
}
this.indentation = indentation;
}
public String toString() {
return "XmlTemplateEngine";
}
}
|
src/main/groovy/text/XmlTemplateEngine.java
|
/*
* Copyright 2003-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 groovy.text;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import groovy.lang.Writable;
import groovy.util.IndentPrinter;
import groovy.util.Node;
import groovy.util.XmlNodePrinter;
import groovy.util.XmlParser;
import groovy.xml.QName;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.xml.sax.SAXException;
/**
* Template engine for xml data input.
*
* @author Christian Stein
* @author Paul King
*/
public class XmlTemplateEngine extends TemplateEngine {
private static class GspPrinter extends XmlNodePrinter {
public GspPrinter(PrintWriter out, String indent) {
this(new IndentPrinter(out, indent));
}
public GspPrinter(IndentPrinter out) {
super(out, "\\\"");
setQuote("'");
}
protected void printGroovyTag(String tag, String text) {
if (tag.equals("scriptlet")) {
out.print(text);
out.print("\n");
return;
}
if (tag.equals("expression")) {
printLineBegin();
out.print("${");
out.print(text);
out.print("}");
printLineEnd();
return;
}
throw new RuntimeException("Unsupported gsp tag named \"" + tag + "\".");
}
protected void printSimpleItem(Object value) {
this.printLineBegin();
out.print(escapeQuote(InvokerHelper.toString(value)));
printLineEnd();
}
private String escapeQuote(String s) {
return s.replaceAll("\"", "\\\\\"");
}
protected void printLineBegin() {
out.print("out.print(\"");
out.printIndent();
}
protected void printLineEnd(String comment) {
out.print("\\n\");");
if (comment != null) {
out.print(" // ");
out.print(comment);
}
out.print("\n");
}
protected boolean printSpecialNode(Node node) {
Object name = node.name();
if (name != null && name instanceof QName) {
QName qn = (QName) name;
if (qn.getPrefix().equals("gsp")) {
String s = qn.getLocalPart();
if (s.length() == 0) {
throw new RuntimeException("No local part after 'gsp:' given in node " + node);
}
printGroovyTag(s, node.text());
return true;
}
}
return false;
}
}
private static class XmlTemplate implements Template {
private final Script script;
public XmlTemplate(Script script) {
this.script = script;
}
public Writable make() {
return make(new HashMap());
}
public Writable make(Map map) {
if (map == null) {
throw new IllegalArgumentException("map must not be null");
}
return new XmlWritable(script, new Binding(map));
}
}
private static class XmlWritable implements Writable {
private final Binding binding;
private final Script script;
private WeakReference result;
public XmlWritable(Script script, Binding binding) {
this.script = script;
this.binding = binding;
this.result = new WeakReference(null);
}
public Writer writeTo(Writer out) {
Script scriptObject = InvokerHelper.createScript(script.getClass(), binding);
PrintWriter pw = new PrintWriter(out);
scriptObject.setProperty("out", pw);
scriptObject.run();
pw.flush();
return out;
}
public String toString() {
if (result.get() != null) {
return result.get().toString();
}
String string = writeTo(new StringWriter(1024)).toString();
result = new WeakReference(string);
return string;
}
}
public static final String DEFAULT_INDENTATION = " ";
private final GroovyShell groovyShell;
private final XmlParser xmlParser;
private String indentation;
public XmlTemplateEngine() throws SAXException, ParserConfigurationException {
this(DEFAULT_INDENTATION, false);
}
public XmlTemplateEngine(String indentation, boolean validating) throws SAXException, ParserConfigurationException {
this(new XmlParser(validating, true), new GroovyShell());
setIndentation(indentation);
}
public XmlTemplateEngine(XmlParser xmlParser, ClassLoader parentLoader) {
this(xmlParser, new GroovyShell(parentLoader));
}
public XmlTemplateEngine(XmlParser xmlParser, GroovyShell groovyShell) {
this.groovyShell = groovyShell;
this.xmlParser = xmlParser;
setIndentation(DEFAULT_INDENTATION);
}
public Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException {
Node root = null;
try {
root = xmlParser.parse(reader);
} catch (SAXException e) {
throw new RuntimeException("Parsing XML source failed.", e);
}
if (root == null) {
throw new IOException("Parsing XML source failed: root node is null.");
}
StringWriter writer = new StringWriter(1024);
writer.write("/* Generated by XmlTemplateEngine */\n");
new GspPrinter(new PrintWriter(writer), indentation).print(root);
Script script = groovyShell.parse(writer.toString());
return new XmlTemplate(script);
}
public String getIndentation() {
return indentation;
}
public void setIndentation(String indentation) {
if (indentation == null) {
indentation = DEFAULT_INDENTATION;
}
this.indentation = indentation;
}
public String toString() {
return "XmlTemplateEngine";
}
}
|
Partial fix for GROOVY-952: XmlTemplateEngine must preserve valid XML files (escape quot, lt, gt and apos entities)
git-svn-id: aa43ce4553b005588bb3cc6c16966320b011facb@10176 a5544e8c-8a19-0410-ba12-f9af4593a198
|
src/main/groovy/text/XmlTemplateEngine.java
|
Partial fix for GROOVY-952: XmlTemplateEngine must preserve valid XML files (escape quot, lt, gt and apos entities)
|
<ide><path>rc/main/groovy/text/XmlTemplateEngine.java
<ide> printLineEnd();
<ide> return;
<ide> }
<del> throw new RuntimeException("Unsupported gsp tag named \"" + tag + "\".");
<add> throw new RuntimeException("Unsupported 'gsp:' tag named \"" + tag + "\".");
<ide> }
<ide>
<ide> protected void printSimpleItem(Object value) {
<ide> this.printLineBegin();
<del> out.print(escapeQuote(InvokerHelper.toString(value)));
<add> out.print(escapeSpecialChars(InvokerHelper.toString(value)));
<ide> printLineEnd();
<ide> }
<ide>
<del> private String escapeQuote(String s) {
<del> return s.replaceAll("\"", "\\\\\"");
<add> private String escapeSpecialChars(String s) {
<add> s = s.replaceAll("\"", """);
<add> s = s.replaceAll("<", "<");
<add> s = s.replaceAll(">", ">");
<add> s = s.replaceAll("'", "'");
<add> return s;
<ide> }
<ide>
<ide> protected void printLineBegin() {
|
|
Java
|
mpl-2.0
|
7bc3b0980013f3e0215a405a56fc8ffdfb5a124a
| 0 |
os2indberetning/OS2_Android
|
package it_minds.dk.eindberetningmobil_android.settings;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import it_minds.dk.eindberetningmobil_android.models.Profile;
import it_minds.dk.eindberetningmobil_android.models.Provider;
import it_minds.dk.eindberetningmobil_android.models.Rates;
import it_minds.dk.eindberetningmobil_android.models.Tokens;
import it_minds.dk.eindberetningmobil_android.models.internal.PrefilledData;
import it_minds.dk.eindberetningmobil_android.models.internal.SaveableReport;
/**
* Created by kasper on 28-06-2015.
* handles all storage on the device, though sharedPrefs (a private one).
*/
public class MainSettings {
//<editor-fold desc="Constants / indexes">
private static final String PREF_NAME = "settings";
private static final String PROVIDER_INDEX = "PROVIDER_INDEX";
private static final String TOKEN_INDEX = "TOKEN_INDEX";
private static final String RATES_INDEX = "RATES_INDEX";
private static final String PROFILES_INDEX = "PROFILES_INDEX";
private static final String SERVICE_INDEX = "SERVICE_INDEX";
private static final String SAVED_REPORTS_INDEX = "SAVED_REPORTS_INDEX";
private static final String PREFILLEDDATA_INDEX = "PREFILLEDDATA_INDEX";
//</editor-fold>
//<editor-fold desc="singleton">
private static MainSettings instance;
private final Context context;
public MainSettings(Context context) {
this.context = context;
}
public static MainSettings getInstance(Context context) {
if (instance == null) {
instance = new MainSettings(context);
}
return instance;
}
//</editor-fold>
//<editor-fold desc="Helper methods">
private SharedPreferences getPrefs() {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
//</editor-fold>
//<editor-fold desc="Provider">
/**
* haveProvider
*
* @return boolean
*/
public boolean haveProvider() {
return getPrefs().getString(PROVIDER_INDEX, null) != null;
}
/**
* getProvider
*
* @return Provider
*/
public Provider getProvider() {
String val = getPrefs().getString(PROVIDER_INDEX, null);
if (val == null) {
return null;
}
try {
return Provider.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* setProvider
*
* @return void
*/
public void setProvider(Provider newVal) {
String json = null;
if (newVal != null) {
json = newVal.saveToJson().toString();
}
getPrefs().edit().putString(PROVIDER_INDEX, json).commit();
}
//</editor-fold>
//<editor-fold desc="token">
/**
* haveToken
*
* @return boolean
*/
public boolean haveToken() {
return getPrefs().getString(TOKEN_INDEX, null) != null;
}
/**
* getToken
*
* @return Tokens
*/
public Tokens getToken() {
String val = getPrefs().getString(TOKEN_INDEX, null);
if (val != null) {
try {
return Tokens.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* setToken
*
* @return void
*/
public void setToken(Tokens newVal) {
getPrefs().edit().putString(TOKEN_INDEX, newVal.saveToJson().toString()).commit();
}
//</editor-fold>
//<editor-fold desc="rates">
public void setRates(ArrayList<Rates> rates) {
//Remove rates that are not used on mobile reporting
for (Rates r : rates){
if (r.getId() == 8){
rates.remove(r);
Log.d("MainSettings - setRates","Removed rate with id: " + r.getId() + " desc: " + r.getDescription());
}
}
JSONArray arr = Rates.saveAllToJson(rates);
getPrefs().edit().putString(RATES_INDEX, arr.toString()).commit();
}
public ArrayList<Rates> getRates() {
String val = getPrefs().getString(RATES_INDEX, null);
if (val != null) {
try {
return Rates.parseAllFromJson(new JSONArray(val));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public Profile getProfile() {
String val = getPrefs().getString(PROFILES_INDEX, null);
if (val != null) {
try {
return Profile.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public void clearProfile() {
getPrefs().edit().remove(PROFILES_INDEX).commit();
}
public void setProfile(Profile profile) {
getPrefs().edit().putString(PROFILES_INDEX, profile.saveToJson().toString()).commit();
}
public void clear() {
getPrefs().edit().clear().commit();
}
public void setServiceClosed(boolean serviceClosed) {
getPrefs().edit().putBoolean(SERVICE_INDEX, serviceClosed).commit();
}
public boolean getServiceClosed() {
return getPrefs().getBoolean(SERVICE_INDEX, true);
}
public void clearToken() {
getPrefs().edit().remove(TOKEN_INDEX).commit();
}
//</editor-fold>
//drive report saving
public void addReport(SaveableReport report) {
List<SaveableReport> drivingReports = getDrivingReports();
drivingReports.add(report);
setSavedReports(drivingReports);
}
public List<SaveableReport> getDrivingReports() {
List<SaveableReport> reports = new ArrayList<>();
String json = getPrefs().getString(SAVED_REPORTS_INDEX, null);
if (json == null) {
return reports;
}
//try parse.
try {
JSONArray arr = new JSONArray(json);
reports = SaveableReport.parseAllFromJson(arr);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return reports;
}
public void removeSavedReport(SaveableReport report) {
List<SaveableReport> drivingReports = getDrivingReports();
drivingReports.remove(report);
setSavedReports(drivingReports);
}
private void setSavedReports(List<SaveableReport> reports) {
//save to json
String json = "";
if (reports != null) {
ArrayList<JSONObject> lst = new ArrayList<>();
for (SaveableReport repo : reports) {
lst.add(repo.saveToJson());
}
json = new JSONArray(lst).toString();
}
getPrefs().edit().putString(SAVED_REPORTS_INDEX, json).commit();
}
public void clearReports() {
getPrefs().edit().remove(SAVED_REPORTS_INDEX).commit();
}
/**
* havePrefilledData description here
*
* @return boolean
*/
public boolean havePrefilledData() {
return getPrefs().getString(PREFILLEDDATA_INDEX, null) != null;
}
/**
* setPrefilledData description here
*
* @return void
*/
public void setPrefilledData(PrefilledData newVal) {
getPrefs().edit().putString(PREFILLEDDATA_INDEX, newVal.saveToJson().toString()).commit();
}
/**
* getPrefilledData description here
*
* @return PrefilledData
*/
public PrefilledData getPrefilledData() {
String val = getPrefs().getString(PREFILLEDDATA_INDEX, null);
if (val == null) {
return null;
}
try {
return PrefilledData.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
app/src/main/java/it_minds/dk/eindberetningmobil_android/settings/MainSettings.java
|
package it_minds.dk.eindberetningmobil_android.settings;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import it_minds.dk.eindberetningmobil_android.models.Profile;
import it_minds.dk.eindberetningmobil_android.models.Provider;
import it_minds.dk.eindberetningmobil_android.models.Rates;
import it_minds.dk.eindberetningmobil_android.models.Tokens;
import it_minds.dk.eindberetningmobil_android.models.internal.PrefilledData;
import it_minds.dk.eindberetningmobil_android.models.internal.SaveableReport;
/**
* Created by kasper on 28-06-2015.
* handles all storage on the device, though sharedPrefs (a private one).
*/
public class MainSettings {
//<editor-fold desc="Constants / indexes">
private static final String PREF_NAME = "settings";
private static final String PROVIDER_INDEX = "PROVIDER_INDEX";
private static final String TOKEN_INDEX = "TOKEN_INDEX";
private static final String RATES_INDEX = "RATES_INDEX";
private static final String PROFILES_INDEX = "PROFILES_INDEX";
private static final String SERVICE_INDEX = "SERVICE_INDEX";
private static final String SAVED_REPORTS_INDEX = "SAVED_REPORTS_INDEX";
private static final String PREFILLEDDATA_INDEX = "PREFILLEDDATA_INDEX";
//</editor-fold>
//<editor-fold desc="singleton">
private static MainSettings instance;
private final Context context;
public MainSettings(Context context) {
this.context = context;
}
public static MainSettings getInstance(Context context) {
if (instance == null) {
instance = new MainSettings(context);
}
return instance;
}
//</editor-fold>
//<editor-fold desc="Helper methods">
private SharedPreferences getPrefs() {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
//</editor-fold>
//<editor-fold desc="Provider">
/**
* haveProvider
*
* @return boolean
*/
public boolean haveProvider() {
return getPrefs().getString(PROVIDER_INDEX, null) != null;
}
/**
* getProvider
*
* @return Provider
*/
public Provider getProvider() {
String val = getPrefs().getString(PROVIDER_INDEX, null);
if (val == null) {
return null;
}
try {
return Provider.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* setProvider
*
* @return void
*/
public void setProvider(Provider newVal) {
String json = null;
if (newVal != null) {
json = newVal.saveToJson().toString();
}
getPrefs().edit().putString(PROVIDER_INDEX, json).commit();
}
//</editor-fold>
//<editor-fold desc="token">
/**
* haveToken
*
* @return boolean
*/
public boolean haveToken() {
return getPrefs().getString(TOKEN_INDEX, null) != null;
}
/**
* getToken
*
* @return Tokens
*/
public Tokens getToken() {
String val = getPrefs().getString(TOKEN_INDEX, null);
if (val != null) {
try {
return Tokens.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* setToken
*
* @return void
*/
public void setToken(Tokens newVal) {
getPrefs().edit().putString(TOKEN_INDEX, newVal.saveToJson().toString()).commit();
}
//</editor-fold>
//<editor-fold desc="rates">
public void setRates(ArrayList<Rates> rates) {
//Remove unwanted rates
for (Rates r : rates){
if (r.getId() == 8){
rates.remove(r);
Log.d("MainSettings - setRates","Removed rate with id: " + r.getId() + " desc: " + r.getDescription());
}
}
JSONArray arr = Rates.saveAllToJson(rates);
getPrefs().edit().putString(RATES_INDEX, arr.toString()).commit();
}
public ArrayList<Rates> getRates() {
String val = getPrefs().getString(RATES_INDEX, null);
if (val != null) {
try {
return Rates.parseAllFromJson(new JSONArray(val));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public Profile getProfile() {
String val = getPrefs().getString(PROFILES_INDEX, null);
if (val != null) {
try {
return Profile.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public void clearProfile() {
getPrefs().edit().remove(PROFILES_INDEX).commit();
}
public void setProfile(Profile profile) {
getPrefs().edit().putString(PROFILES_INDEX, profile.saveToJson().toString()).commit();
}
public void clear() {
getPrefs().edit().clear().commit();
}
public void setServiceClosed(boolean serviceClosed) {
getPrefs().edit().putBoolean(SERVICE_INDEX, serviceClosed).commit();
}
public boolean getServiceClosed() {
return getPrefs().getBoolean(SERVICE_INDEX, true);
}
public void clearToken() {
getPrefs().edit().remove(TOKEN_INDEX).commit();
}
//</editor-fold>
//drive report saving
public void addReport(SaveableReport report) {
List<SaveableReport> drivingReports = getDrivingReports();
drivingReports.add(report);
setSavedReports(drivingReports);
}
public List<SaveableReport> getDrivingReports() {
List<SaveableReport> reports = new ArrayList<>();
String json = getPrefs().getString(SAVED_REPORTS_INDEX, null);
if (json == null) {
return reports;
}
//try parse.
try {
JSONArray arr = new JSONArray(json);
reports = SaveableReport.parseAllFromJson(arr);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return reports;
}
public void removeSavedReport(SaveableReport report) {
List<SaveableReport> drivingReports = getDrivingReports();
drivingReports.remove(report);
setSavedReports(drivingReports);
}
private void setSavedReports(List<SaveableReport> reports) {
//save to json
String json = "";
if (reports != null) {
ArrayList<JSONObject> lst = new ArrayList<>();
for (SaveableReport repo : reports) {
lst.add(repo.saveToJson());
}
json = new JSONArray(lst).toString();
}
getPrefs().edit().putString(SAVED_REPORTS_INDEX, json).commit();
}
public void clearReports() {
getPrefs().edit().remove(SAVED_REPORTS_INDEX).commit();
}
/**
* havePrefilledData description here
*
* @return boolean
*/
public boolean havePrefilledData() {
return getPrefs().getString(PREFILLEDDATA_INDEX, null) != null;
}
/**
* setPrefilledData description here
*
* @return void
*/
public void setPrefilledData(PrefilledData newVal) {
getPrefs().edit().putString(PREFILLEDDATA_INDEX, newVal.saveToJson().toString()).commit();
}
/**
* getPrefilledData description here
*
* @return PrefilledData
*/
public PrefilledData getPrefilledData() {
String val = getPrefs().getString(PREFILLEDDATA_INDEX, null);
if (val == null) {
return null;
}
try {
return PrefilledData.parseFromJson(new JSONObject(val));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
Added comment for clarification when removing Anhænger (rateId = 8)
|
app/src/main/java/it_minds/dk/eindberetningmobil_android/settings/MainSettings.java
|
Added comment for clarification when removing Anhænger (rateId = 8)
|
<ide><path>pp/src/main/java/it_minds/dk/eindberetningmobil_android/settings/MainSettings.java
<ide> //<editor-fold desc="rates">
<ide> public void setRates(ArrayList<Rates> rates) {
<ide>
<del> //Remove unwanted rates
<add> //Remove rates that are not used on mobile reporting
<ide> for (Rates r : rates){
<ide> if (r.getId() == 8){
<ide> rates.remove(r);
|
|
Java
|
bsd-3-clause
|
50abca021a8928589942da88b6fa33f9d8f537d3
| 0 |
HaraldWalker/user-agent-utils,pcollaog/user-agent-utils,nhojpatrick/user-agent-utils
|
/*
* Copyright (c) 2008-2016, Harald Walker (bitwalker.eu) and contributing developers
* 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 bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.bitwalker.useragentutils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Enum constants for most common operating systems.
* @author harald
*/
public enum OperatingSystem {
// the order is important since the agent string is being compared with the aliases
/**
* Windows Mobile / Windows CE. Exact version unknown.
*/
WINDOWS( Manufacturer.MICROSOFT,null,1, "Windows", new String[] { "Windows" }, new String[] { "Palm", "ggpht.com" }, DeviceType.COMPUTER, null ), // catch the rest of older Windows systems (95, NT,...)
WINDOWS_10( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,24, "Windows 10", new String[] { "Windows NT 6.4", "Windows NT 10" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 10 is called 6.4 LOL
WINDOWS_81( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,23, "Windows 8.1", new String[] { "Windows NT 6.3" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 8.1 is called 6.3 LOL
WINDOWS_8( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,22, "Windows 8", new String[] { "Windows NT 6.2" }, new String[]{"Xbox","Xbox One"}, DeviceType.COMPUTER, null ), // before Win, yes, Windows 8 is called 6.2 LOL
WINDOWS_7( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,21, "Windows 7", new String[] { "Windows NT 6.1" }, new String[]{"Xbox","Xbox One"}, DeviceType.COMPUTER, null ), // before Win, yes, Windows 7 is called 6.1 LOL
WINDOWS_VISTA( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,20, "Windows Vista", new String[] { "Windows NT 6" }, new String[]{"Xbox","Xbox One"}, DeviceType.COMPUTER, null ), // before Win
WINDOWS_2000( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,15, "Windows 2000", new String[] { "Windows NT 5.0" }, null, DeviceType.COMPUTER, null ), // before Win
WINDOWS_XP( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,10, "Windows XP", new String[] { "Windows NT 5"}, new String[] { "ggpht.com" }, DeviceType.COMPUTER, null ), // before Win, 5.1 and 5.2 are basically XP systems
WINDOWS_10_MOBILE(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 54, "Windows 10 Mobile", new String[] { "Windows Phone 10" }, null, DeviceType.MOBILE, null ),
WINDOWS_PHONE8_1(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 53, "Windows Phone 8.1", new String[] { "Windows Phone 8.1" }, null, DeviceType.MOBILE, null ), // before Win
WINDOWS_PHONE8(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 52, "Windows Phone 8", new String[] { "Windows Phone 8" }, null, DeviceType.MOBILE, null ), // before Win
WINDOWS_MOBILE7(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 51, "Windows Phone 7", new String[] { "Windows Phone OS 7" }, null, DeviceType.MOBILE, null ), // should be Windows Phone 7 but to keep it compatible we'll leave the name as is.
WINDOWS_MOBILE( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 50, "Windows Mobile", new String[] { "Windows CE" }, null, DeviceType.MOBILE, null ), // before Win
WINDOWS_98( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,5, "Windows 98", new String[] { "Windows 98","Win98" }, new String[] { "Palm" }, DeviceType.COMPUTER, null ), // before Win
XBOX_OS(Manufacturer.MICROSOFT, OperatingSystem.WINDOWS,62, "Xbox OS",new String[]{"xbox"},new String[]{}, DeviceType.GAME_CONSOLE, null),
// for Google user-agent, see https://developer.chrome.com/multidevice/user-agent
ANDROID( Manufacturer.GOOGLE,null, 0, "Android", new String[] { "Android" }, new String[] {"Ubuntu"}, DeviceType.MOBILE, null ),
ANDROID8( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 8, "Android 8.x", new String[] { "Android 8", "Android-8" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
ANDROID8_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID8, 80, "Android 8.x Tablet", new String[] { "Android 8", "Android-8"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
ANDROID7( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 7, "Android 7.x", new String[] { "Android 7", "Android-7" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
ANDROID7_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID7, 70, "Android 7.x Tablet", new String[] { "Android 7", "Android-7"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
ANDROID6( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 6, "Android 6.x", new String[] { "Android 6", "Android-6" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
ANDROID6_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID6, 60, "Android 6.x Tablet", new String[] { "Android 6", "Android-6"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
ANDROID5( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 5, "Android 5.x", new String[] { "Android 5", "Android-5" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
ANDROID5_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID5, 50, "Android 5.x Tablet", new String[] { "Android 5", "Android-5"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
ANDROID4( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 4, "Android 4.x", new String[] { "Android 4", "Android-4" }, new String[] { "glass", "ubuntu"}, DeviceType.MOBILE, null ),
ANDROID4_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID4, 40, "Android 4.x Tablet", new String[] { "Android 4", "Android-4"}, new String[] { "mobile", "glass", "ubuntu" }, DeviceType.TABLET, null ),
ANDROID4_WEARABLE(Manufacturer.GOOGLE,OperatingSystem.ANDROID, 400, "Android 4.x", new String[] { "Android 4" }, new String[] {"ubuntu"}, DeviceType.WEARABLE, null ),
ANDROID3_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID, 30, "Android 3.x Tablet", new String[] { "Android 3" }, null, DeviceType.TABLET, null ), // as long as there are not Android 3.x phones this should be enough
ANDROID2( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 2, "Android 2.x", new String[] { "Android 2" }, null, DeviceType.MOBILE, null ),
ANDROID2_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID2, 20, "Android 2.x Tablet", new String[] { "Kindle Fire", "GT-P1000","SCH-I800" }, null, DeviceType.TABLET, null ),
ANDROID1( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 1, "Android 1.x", new String[] { "Android 1" }, null, DeviceType.MOBILE, null ),
/**
* Generic Android mobile device without OS version number information
*/
ANDROID_MOBILE( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 11, "Android Mobile", new String[] { "Mobile" }, new String[] {"ubuntu"}, DeviceType.MOBILE, null ),
/**
* Generic Android tablet device without OS version number information
*/
ANDROID_TABLET( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 12, "Android Tablet", new String[] { "Tablet" }, null, DeviceType.TABLET, null ),
/**
* Chrome OS by Google, mostly used on Chromebooks and Chromeboxes
*/
CHROME_OS( Manufacturer.GOOGLE,null, 1000, "Chrome OS", new String[] { "CrOS" }, null, DeviceType.COMPUTER, null ),
/**
* PalmOS, exact version unkown
*/
WEBOS( Manufacturer.HP,null,11, "WebOS", new String[] { "webOS" }, null, DeviceType.MOBILE, null ),
PALM( Manufacturer.HP,null,10, "PalmOS", new String[] { "Palm" }, null, DeviceType.MOBILE, null ),
MEEGO( Manufacturer.NOKIA,null,3, "MeeGo", new String[] { "MeeGo" }, null, DeviceType.MOBILE, null ),
/**
* iOS4, with the release of the iPhone 4, Apple renamed the OS to iOS.
*/
IOS( Manufacturer.APPLE,null, 2, "iOS", new String[] { "iPhone", "like Mac OS X" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS9_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 90, "iOS 9 (iPhone)", new String[] { "iPhone OS 9" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_4_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 49, "iOS 8.4 (iPhone)", new String[] { "iPhone OS 8_4" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_3_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 48, "iOS 8.3 (iPhone)", new String[] { "iPhone OS 8_3" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_2_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 47, "iOS 8.2 (iPhone)", new String[] { "iPhone OS 8_2" }, null, DeviceType.MOBILE, null ), // version that added Apple Watch support
iOS8_1_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 46, "iOS 8.1 (iPhone)", new String[] { "iPhone OS 8_1" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 45, "iOS 8 (iPhone)", new String[] { "iPhone OS 8" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS7_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 44, "iOS 7 (iPhone)", new String[] { "iPhone OS 7" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS6_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 43, "iOS 6 (iPhone)", new String[] { "iPhone OS 6" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS5_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 42, "iOS 5 (iPhone)", new String[] { "iPhone OS 5" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS4_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 41, "iOS 4 (iPhone)", new String[] { "iPhone OS 4" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
MAC_OS_X_IPAD( Manufacturer.APPLE, OperatingSystem.IOS, 50, "Mac OS X (iPad)", new String[] { "iPad" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS9_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 58, "iOS 9 (iPad)", new String[] { "OS 9" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_4_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 57, "iOS 8.4 (iPad)", new String[] { "OS 8_4" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_3_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 56, "iOS 8.3 (iPad)", new String[] { "OS 8_3" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_2_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 55, "iOS 8.2 (iPad)", new String[] { "OS 8_2" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_1_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 54, "iOS 8.1 (iPad)", new String[] { "OS 8_1" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 53, "iOS 8 (iPad)", new String[] { "OS 8_0" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS7_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 52, "iOS 7 (iPad)", new String[] { "OS 7" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS6_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 51, "iOS 6 (iPad)", new String[] { "OS 6" }, null, DeviceType.TABLET, null ), // before Mac OS X
MAC_OS_X_IPHONE(Manufacturer.APPLE, OperatingSystem.IOS, 40, "Mac OS X (iPhone)", new String[] { "iPhone" }, null, DeviceType.MOBILE, null ), // before Mac OS X
MAC_OS_X_IPOD( Manufacturer.APPLE, OperatingSystem.IOS, 30, "Mac OS X (iPod)", new String[] { "iPod" }, null, DeviceType.MOBILE, null ), // before Mac OS X
MAC_OS_X( Manufacturer.APPLE,null, 10, "Mac OS X", new String[] { "Mac OS X" , "CFNetwork"}, null, DeviceType.COMPUTER, null ), // before Mac
/**
* Older Mac OS systems before Mac OS X
*/
MAC_OS( Manufacturer.APPLE,null, 1, "Mac OS", new String[] { "Mac" }, null, DeviceType.COMPUTER, null ), // older Mac OS systems
/**
* Linux based Maemo software platform by Nokia. Used in the N900 phone. http://maemo.nokia.com/
*/
MAEMO( Manufacturer.NOKIA,null, 2, "Maemo", new String[] { "Maemo" }, null, DeviceType.MOBILE, null ),
/**
* Bada is a mobile operating system being developed by Samsung Electronics.
*/
BADA( Manufacturer.SAMSUNG,null, 2, "Bada", new String[] { "Bada" }, null, DeviceType.MOBILE, null ),
/**
* Google TV uses Android 2.x or 3.x but doesn't identify itself as Android.
*/
GOOGLE_TV( Manufacturer.GOOGLE,null, 100, "Android (Google TV)", new String[] { "GoogleTV" }, null, DeviceType.DMR, null ),
/**
* Various Linux based operating systems.
*/
KINDLE( Manufacturer.AMAZON,null, 1, "Linux (Kindle)", new String[] { "Kindle" }, null, DeviceType.TABLET, null ),
KINDLE3( Manufacturer.AMAZON,OperatingSystem.KINDLE, 30, "Linux (Kindle 3)", new String[] { "Kindle/3" }, null, DeviceType.TABLET, null ),
KINDLE2( Manufacturer.AMAZON,OperatingSystem.KINDLE, 20, "Linux (Kindle 2)", new String[] { "Kindle/2" }, null, DeviceType.TABLET, null ),
LINUX( Manufacturer.OTHER,null, 2, "Linux", new String[] { "Linux", "CamelHttpStream" }, null, DeviceType.COMPUTER, null ), // CamelHttpStream is being used by Evolution, an email client for Linux
UBUNTU( Manufacturer.CONONICAL, OperatingSystem.LINUX, 1, "Ubuntu", new String[] {"ubuntu"}, null, DeviceType.COMPUTER, null),
UBUNTU_TOUCH_MOBILE( Manufacturer.CONONICAL, OperatingSystem.UBUNTU, 200, "Ubuntu Touch (mobile)", new String[] {"mobile"}, null, DeviceType.MOBILE, null),
/**
* Other Symbian OS versions
*/
SYMBIAN( Manufacturer.SYMBIAN,null, 1, "Symbian OS", new String[] { "Symbian", "Series60"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 9.x versions. Being used by Nokia (N71, N73, N81, N82, N91, N92, N95, ...)
*/
SYMBIAN9( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 20, "Symbian OS 9.x", new String[] {"SymbianOS/9", "Series60/3"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 8.x versions. Being used by Nokia (6630, 6680, 6681, 6682, N70, N72, N90).
*/
SYMBIAN8( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 15, "Symbian OS 8.x", new String[] { "SymbianOS/8", "Series60/2.6", "Series60/2.8"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 7.x versions. Being used by Nokia (3230, 6260, 6600, 6620, 6670, 7610),
* Panasonic (X700, X800), Samsung (SGH-D720, SGH-D730) and Lenovo (P930).
*/
SYMBIAN7( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 10, "Symbian OS 7.x", new String[] { "SymbianOS/7"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 6.x versions.
*/
SYMBIAN6( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 5, "Symbian OS 6.x", new String[] { "SymbianOS/6"}, null, DeviceType.MOBILE, null ),
/**
* Nokia's Series 40 operating system. Series 60 (S60) uses the Symbian OS.
*/
SERIES40 ( Manufacturer.NOKIA,null, 1, "Series 40", new String[] { "Nokia6300"}, null, DeviceType.MOBILE, null ),
/**
* Proprietary operating system used for many Sony Ericsson phones.
*/
SONY_ERICSSON ( Manufacturer.SONY_ERICSSON, null, 1, "Sony Ericsson", new String[] { "SonyEricsson"}, null, DeviceType.MOBILE, null ), // after symbian, some SE phones use symbian
SUN_OS( Manufacturer.SUN, null, 1, "SunOS", new String[] { "SunOS" } , null, DeviceType.COMPUTER, null ),
PSP( Manufacturer.SONY, null, 1, "Sony Playstation", new String[] { "Playstation" }, null, DeviceType.GAME_CONSOLE, null ),
/**
* Nintendo Wii game console.
*/
WII( Manufacturer.NINTENDO,null, 1, "Nintendo Wii", new String[] { "Wii" }, null, DeviceType.GAME_CONSOLE, null ),
/**
* BlackBerryOS. The BlackBerryOS exists in different version. How relevant those versions are, is not clear.
*/
BLACKBERRY( Manufacturer.BLACKBERRY,null, 1, "BlackBerryOS", new String[] { "BlackBerry" }, null, DeviceType.MOBILE, null ),
BLACKBERRY7( Manufacturer.BLACKBERRY,OperatingSystem.BLACKBERRY, 7, "BlackBerry 7", new String[] { "Version/7" }, null, DeviceType.MOBILE, null ),
BLACKBERRY6( Manufacturer.BLACKBERRY,OperatingSystem.BLACKBERRY, 6, "BlackBerry 6", new String[] { "Version/6" }, null, DeviceType.MOBILE, null ),
BLACKBERRY_TABLET(Manufacturer.BLACKBERRY,null, 100, "BlackBerry Tablet OS", new String[] { "RIM Tablet OS" }, null, DeviceType.TABLET, null ),
ROKU( Manufacturer.ROKU,null, 1, "Roku OS", new String[] { "Roku" }, null, DeviceType.DMR, null ),
/**
* Proxy server that hides the original user-agent.
* ggpht.com = Gmail proxy server
*/
PROXY( Manufacturer.OTHER,null, 10, "Proxy", new String[] { "ggpht.com" }, null, DeviceType.UNKNOWN, null ),
UNKNOWN_MOBILE( Manufacturer.OTHER,null, 3, "Unknown mobile", new String[] {"Mobile"}, null, DeviceType.MOBILE, null ),
UNKNOWN_TABLET( Manufacturer.OTHER,null, 4, "Unknown tablet", new String[] {"Tablet"}, null, DeviceType.TABLET, null ),
UNKNOWN( Manufacturer.OTHER,null, 1, "Unknown", new String[0], null, DeviceType.UNKNOWN, null );
private final short id;
private final String name;
private final String[] aliases;
private final String[] excludeList; // don't match when these values are in the agent-string
private final Manufacturer manufacturer;
private final DeviceType deviceType;
private final OperatingSystem parent;
private List<OperatingSystem> children;
private Pattern versionRegEx;
private static List<OperatingSystem> topLevelOperatingSystems;
private OperatingSystem(Manufacturer manufacturer, OperatingSystem parent, int versionId, String name,
String[] aliases,
String[] exclude, DeviceType deviceType, String versionRegexString) {
this.manufacturer = manufacturer;
this.parent = parent;
this.children = new ArrayList<OperatingSystem>();
// combine manufacturer and version id to one unique id.
this.id = (short) ((manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.aliases = Utils.toLowerCase(aliases);
this.excludeList = Utils.toLowerCase(exclude);
this.deviceType = deviceType;
if (versionRegexString != null) { // not implemented yet
this.versionRegEx = Pattern.compile(versionRegexString);
}
if (this.parent == null)
addTopLevelOperatingSystem(this);
else
this.parent.children.add(this);
}
// create collection of top level operating systems during initialization
private static void addTopLevelOperatingSystem(OperatingSystem os) {
if(topLevelOperatingSystems == null)
topLevelOperatingSystems = new ArrayList<OperatingSystem>();
topLevelOperatingSystems.add(os);
}
public short getId() {
return id;
}
public String getName() {
return name;
}
/*
* Shortcut to check of an operating system is a mobile device.
* Left in here for backwards compatibility. Use .getDeviceType() instead.
*/
@Deprecated
public boolean isMobileDevice() {
return deviceType.equals(DeviceType.MOBILE);
}
public DeviceType getDeviceType() {
return deviceType;
}
/*
* Gets the top level grouping operating system
*/
public OperatingSystem getGroup() {
if (this.parent != null) {
return parent.getGroup();
}
return this;
}
/**
* Returns the manufacturer of the operating system
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/**
* Checks if the given user-agent string matches to the operating system.
* Only checks for one specific operating system.
* @param agentString
* @return boolean
*/
public boolean isInUserAgentString(String agentString)
{
if (agentString == null) {
return false;
}
final String agentLowerCaseString = agentString.toLowerCase();
return isInUserAgentStringLowercase(agentLowerCaseString);
}
private boolean isInUserAgentStringLowercase(final String agentLowerCaseString) {
return Utils.contains(agentLowerCaseString, aliases);
}
/**
* Checks if the given user-agent does not contain one of the tokens which should not match.
* In most cases there are no excluding tokens, so the impact should be small.
* @param agentLowerCaseString
* @return
*/
private boolean containsExcludeTokenLowercase(final String agentLowerCaseString) {
return Utils.contains(agentLowerCaseString, excludeList);
}
private OperatingSystem checkUserAgentLowercase(String agentStringLowercase) {
if (this.isInUserAgentStringLowercase(agentStringLowercase)) {
if (this.children.size() > 0) {
for (OperatingSystem childOperatingSystem : this.children) {
OperatingSystem match = childOperatingSystem.checkUserAgentLowercase(agentStringLowercase);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!this.containsExcludeTokenLowercase(agentStringLowercase)) {
return this;
}
}
return null;
}
/**
* Parses user agent string and returns the best match.
* Returns OperatingSystem.UNKNOWN if there is no match.
* @param agentString
* @return OperatingSystem
*/
public static OperatingSystem parseUserAgentString(String agentString)
{
return parseUserAgentString(agentString, topLevelOperatingSystems);
}
public static OperatingSystem parseUserAgentLowercaseString(String agentString)
{
if (agentString == null) {
return OperatingSystem.UNKNOWN;
}
return parseUserAgentLowercaseString(agentString, topLevelOperatingSystems);
}
/**
* Parses the user agent string and returns the best match for the given operating systems.
* Returns OperatingSystem.UNKNOWN if there is no match.
* Be aware that if the order of the provided operating systems is incorrect or the set is too limited it can lead to false matches!
* @param agentString
* @return OperatingSystem
*/
public static OperatingSystem parseUserAgentString(String agentString, List<OperatingSystem> operatingSystems)
{
if (agentString != null) {
final String agentLowercaseString = agentString.toLowerCase();
return parseUserAgentLowercaseString(agentLowercaseString, operatingSystems);
}
return OperatingSystem.UNKNOWN;
}
private static OperatingSystem parseUserAgentLowercaseString(final String agentLowercaseString,
List<OperatingSystem> operatingSystems) {
for (OperatingSystem operatingSystem : operatingSystems)
{
OperatingSystem match = operatingSystem.checkUserAgentLowercase(agentLowercaseString);
if (match != null) {
return match; // either current operatingSystem or a child object
}
}
return OperatingSystem.UNKNOWN;
}
/**
* Returns the enum constant of this type with the specified id.
* Throws IllegalArgumentException if the value does not exist.
* @param id
* @return
*/
public static OperatingSystem valueOf(short id)
{
for (OperatingSystem operatingSystem : OperatingSystem.values())
{
if (operatingSystem.getId() == id)
return operatingSystem;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException(
"No enum const for id " + id);
}
}
|
src/main/java/eu/bitwalker/useragentutils/OperatingSystem.java
|
/*
* Copyright (c) 2008-2016, Harald Walker (bitwalker.eu) and contributing developers
* 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 bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.bitwalker.useragentutils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Enum constants for most common operating systems.
* @author harald
*/
public enum OperatingSystem {
// the order is important since the agent string is being compared with the aliases
/**
* Windows Mobile / Windows CE. Exact version unknown.
*/
WINDOWS( Manufacturer.MICROSOFT,null,1, "Windows", new String[] { "Windows" }, new String[] { "Palm", "ggpht.com" }, DeviceType.COMPUTER, null ), // catch the rest of older Windows systems (95, NT,...)
WINDOWS_10( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,24, "Windows 10", new String[] { "Windows NT 6.4", "Windows NT 10" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 10 is called 6.4 LOL
WINDOWS_81( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,23, "Windows 8.1", new String[] { "Windows NT 6.3" }, null, DeviceType.COMPUTER, null ), // before Win, yes, Windows 8.1 is called 6.3 LOL
WINDOWS_8( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,22, "Windows 8", new String[] { "Windows NT 6.2" }, new String[]{"Xbox","Xbox One"}, DeviceType.COMPUTER, null ), // before Win, yes, Windows 8 is called 6.2 LOL
WINDOWS_7( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,21, "Windows 7", new String[] { "Windows NT 6.1" }, new String[]{"Xbox","Xbox One"}, DeviceType.COMPUTER, null ), // before Win, yes, Windows 7 is called 6.1 LOL
WINDOWS_VISTA( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,20, "Windows Vista", new String[] { "Windows NT 6" }, new String[]{"Xbox","Xbox One"}, DeviceType.COMPUTER, null ), // before Win
WINDOWS_2000( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,15, "Windows 2000", new String[] { "Windows NT 5.0" }, null, DeviceType.COMPUTER, null ), // before Win
WINDOWS_XP( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,10, "Windows XP", new String[] { "Windows NT 5"}, new String[] { "ggpht.com" }, DeviceType.COMPUTER, null ), // before Win, 5.1 and 5.2 are basically XP systems
WINDOWS_10_MOBILE(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 54, "Windows 10 Mobile", new String[] { "Windows Phone 10" }, null, DeviceType.MOBILE, null ),
WINDOWS_PHONE8_1(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 53, "Windows Phone 8.1", new String[] { "Windows Phone 8.1" }, null, DeviceType.MOBILE, null ), // before Win
WINDOWS_PHONE8(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 52, "Windows Phone 8", new String[] { "Windows Phone 8" }, null, DeviceType.MOBILE, null ), // before Win
WINDOWS_MOBILE7(Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 51, "Windows Phone 7", new String[] { "Windows Phone OS 7" }, null, DeviceType.MOBILE, null ), // should be Windows Phone 7 but to keep it compatible we'll leave the name as is.
WINDOWS_MOBILE( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 50, "Windows Mobile", new String[] { "Windows CE" }, null, DeviceType.MOBILE, null ), // before Win
WINDOWS_98( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,5, "Windows 98", new String[] { "Windows 98","Win98" }, new String[] { "Palm" }, DeviceType.COMPUTER, null ), // before Win
XBOX_OS(Manufacturer.MICROSOFT, OperatingSystem.WINDOWS,62, "Xbox OS",new String[]{"xbox"},new String[]{}, DeviceType.GAME_CONSOLE, null),
ANDROID( Manufacturer.GOOGLE,null, 0, "Android", new String[] { "Android" }, new String[] {"Ubuntu"}, DeviceType.MOBILE, null ),
ANDROID6( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 6, "Android 6.x", new String[] { "Android 6", "Android-6" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
ANDROID6_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID6, 60, "Android 6.x Tablet", new String[] { "Android 6", "Android-6"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
ANDROID5( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 5, "Android 5.x", new String[] { "Android 5", "Android-5" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
ANDROID5_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID5, 50, "Android 5.x Tablet", new String[] { "Android 5", "Android-5"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
ANDROID4( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 4, "Android 4.x", new String[] { "Android 4", "Android-4" }, new String[] { "glass", "ubuntu"}, DeviceType.MOBILE, null ),
ANDROID4_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID4, 40, "Android 4.x Tablet", new String[] { "Android 4", "Android-4"}, new String[] { "mobile", "glass", "ubuntu" }, DeviceType.TABLET, null ),
ANDROID4_WEARABLE(Manufacturer.GOOGLE,OperatingSystem.ANDROID, 400, "Android 4.x", new String[] { "Android 4" }, new String[] {"ubuntu"}, DeviceType.WEARABLE, null ),
ANDROID3_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID, 30, "Android 3.x Tablet", new String[] { "Android 3" }, null, DeviceType.TABLET, null ), // as long as there are not Android 3.x phones this should be enough
ANDROID2( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 2, "Android 2.x", new String[] { "Android 2" }, null, DeviceType.MOBILE, null ),
ANDROID2_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID2, 20, "Android 2.x Tablet", new String[] { "Kindle Fire", "GT-P1000","SCH-I800" }, null, DeviceType.TABLET, null ),
ANDROID1( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 1, "Android 1.x", new String[] { "Android 1" }, null, DeviceType.MOBILE, null ),
/**
* Generic Android mobile device without OS version number information
*/
ANDROID_MOBILE( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 11, "Android Mobile", new String[] { "Mobile" }, new String[] {"ubuntu"}, DeviceType.MOBILE, null ),
/**
* Generic Android tablet device without OS version number information
*/
ANDROID_TABLET( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 12, "Android Tablet", new String[] { "Tablet" }, null, DeviceType.TABLET, null ),
/**
* Chrome OS by Google, mostly used on Chromebooks and Chromeboxes
*/
CHROME_OS( Manufacturer.GOOGLE,null, 1000, "Chrome OS", new String[] { "CrOS" }, null, DeviceType.COMPUTER, null ),
/**
* PalmOS, exact version unkown
*/
WEBOS( Manufacturer.HP,null,11, "WebOS", new String[] { "webOS" }, null, DeviceType.MOBILE, null ),
PALM( Manufacturer.HP,null,10, "PalmOS", new String[] { "Palm" }, null, DeviceType.MOBILE, null ),
MEEGO( Manufacturer.NOKIA,null,3, "MeeGo", new String[] { "MeeGo" }, null, DeviceType.MOBILE, null ),
/**
* iOS4, with the release of the iPhone 4, Apple renamed the OS to iOS.
*/
IOS( Manufacturer.APPLE,null, 2, "iOS", new String[] { "iPhone", "like Mac OS X" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS9_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 90, "iOS 9 (iPhone)", new String[] { "iPhone OS 9" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_4_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 49, "iOS 8.4 (iPhone)", new String[] { "iPhone OS 8_4" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_3_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 48, "iOS 8.3 (iPhone)", new String[] { "iPhone OS 8_3" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_2_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 47, "iOS 8.2 (iPhone)", new String[] { "iPhone OS 8_2" }, null, DeviceType.MOBILE, null ), // version that added Apple Watch support
iOS8_1_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 46, "iOS 8.1 (iPhone)", new String[] { "iPhone OS 8_1" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS8_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 45, "iOS 8 (iPhone)", new String[] { "iPhone OS 8" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS7_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 44, "iOS 7 (iPhone)", new String[] { "iPhone OS 7" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS6_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 43, "iOS 6 (iPhone)", new String[] { "iPhone OS 6" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS5_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 42, "iOS 5 (iPhone)", new String[] { "iPhone OS 5" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
iOS4_IPHONE( Manufacturer.APPLE,OperatingSystem.IOS, 41, "iOS 4 (iPhone)", new String[] { "iPhone OS 4" }, null, DeviceType.MOBILE, null ), // before MAC_OS_X_IPHONE for all older versions
MAC_OS_X_IPAD( Manufacturer.APPLE, OperatingSystem.IOS, 50, "Mac OS X (iPad)", new String[] { "iPad" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS9_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 58, "iOS 9 (iPad)", new String[] { "OS 9" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_4_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 57, "iOS 8.4 (iPad)", new String[] { "OS 8_4" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_3_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 56, "iOS 8.3 (iPad)", new String[] { "OS 8_3" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_2_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 55, "iOS 8.2 (iPad)", new String[] { "OS 8_2" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_1_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 54, "iOS 8.1 (iPad)", new String[] { "OS 8_1" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS8_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 53, "iOS 8 (iPad)", new String[] { "OS 8_0" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS7_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 52, "iOS 7 (iPad)", new String[] { "OS 7" }, null, DeviceType.TABLET, null ), // before Mac OS X
iOS6_IPAD( Manufacturer.APPLE, OperatingSystem.MAC_OS_X_IPAD, 51, "iOS 6 (iPad)", new String[] { "OS 6" }, null, DeviceType.TABLET, null ), // before Mac OS X
MAC_OS_X_IPHONE(Manufacturer.APPLE, OperatingSystem.IOS, 40, "Mac OS X (iPhone)", new String[] { "iPhone" }, null, DeviceType.MOBILE, null ), // before Mac OS X
MAC_OS_X_IPOD( Manufacturer.APPLE, OperatingSystem.IOS, 30, "Mac OS X (iPod)", new String[] { "iPod" }, null, DeviceType.MOBILE, null ), // before Mac OS X
MAC_OS_X( Manufacturer.APPLE,null, 10, "Mac OS X", new String[] { "Mac OS X" , "CFNetwork"}, null, DeviceType.COMPUTER, null ), // before Mac
/**
* Older Mac OS systems before Mac OS X
*/
MAC_OS( Manufacturer.APPLE,null, 1, "Mac OS", new String[] { "Mac" }, null, DeviceType.COMPUTER, null ), // older Mac OS systems
/**
* Linux based Maemo software platform by Nokia. Used in the N900 phone. http://maemo.nokia.com/
*/
MAEMO( Manufacturer.NOKIA,null, 2, "Maemo", new String[] { "Maemo" }, null, DeviceType.MOBILE, null ),
/**
* Bada is a mobile operating system being developed by Samsung Electronics.
*/
BADA( Manufacturer.SAMSUNG,null, 2, "Bada", new String[] { "Bada" }, null, DeviceType.MOBILE, null ),
/**
* Google TV uses Android 2.x or 3.x but doesn't identify itself as Android.
*/
GOOGLE_TV( Manufacturer.GOOGLE,null, 100, "Android (Google TV)", new String[] { "GoogleTV" }, null, DeviceType.DMR, null ),
/**
* Various Linux based operating systems.
*/
KINDLE( Manufacturer.AMAZON,null, 1, "Linux (Kindle)", new String[] { "Kindle" }, null, DeviceType.TABLET, null ),
KINDLE3( Manufacturer.AMAZON,OperatingSystem.KINDLE, 30, "Linux (Kindle 3)", new String[] { "Kindle/3" }, null, DeviceType.TABLET, null ),
KINDLE2( Manufacturer.AMAZON,OperatingSystem.KINDLE, 20, "Linux (Kindle 2)", new String[] { "Kindle/2" }, null, DeviceType.TABLET, null ),
LINUX( Manufacturer.OTHER,null, 2, "Linux", new String[] { "Linux", "CamelHttpStream" }, null, DeviceType.COMPUTER, null ), // CamelHttpStream is being used by Evolution, an email client for Linux
UBUNTU( Manufacturer.CONONICAL, OperatingSystem.LINUX, 1, "Ubuntu", new String[] {"ubuntu"}, null, DeviceType.COMPUTER, null),
UBUNTU_TOUCH_MOBILE( Manufacturer.CONONICAL, OperatingSystem.UBUNTU, 200, "Ubuntu Touch (mobile)", new String[] {"mobile"}, null, DeviceType.MOBILE, null),
/**
* Other Symbian OS versions
*/
SYMBIAN( Manufacturer.SYMBIAN,null, 1, "Symbian OS", new String[] { "Symbian", "Series60"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 9.x versions. Being used by Nokia (N71, N73, N81, N82, N91, N92, N95, ...)
*/
SYMBIAN9( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 20, "Symbian OS 9.x", new String[] {"SymbianOS/9", "Series60/3"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 8.x versions. Being used by Nokia (6630, 6680, 6681, 6682, N70, N72, N90).
*/
SYMBIAN8( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 15, "Symbian OS 8.x", new String[] { "SymbianOS/8", "Series60/2.6", "Series60/2.8"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 7.x versions. Being used by Nokia (3230, 6260, 6600, 6620, 6670, 7610),
* Panasonic (X700, X800), Samsung (SGH-D720, SGH-D730) and Lenovo (P930).
*/
SYMBIAN7( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 10, "Symbian OS 7.x", new String[] { "SymbianOS/7"}, null, DeviceType.MOBILE, null ),
/**
* Symbian OS 6.x versions.
*/
SYMBIAN6( Manufacturer.SYMBIAN,OperatingSystem.SYMBIAN, 5, "Symbian OS 6.x", new String[] { "SymbianOS/6"}, null, DeviceType.MOBILE, null ),
/**
* Nokia's Series 40 operating system. Series 60 (S60) uses the Symbian OS.
*/
SERIES40 ( Manufacturer.NOKIA,null, 1, "Series 40", new String[] { "Nokia6300"}, null, DeviceType.MOBILE, null ),
/**
* Proprietary operating system used for many Sony Ericsson phones.
*/
SONY_ERICSSON ( Manufacturer.SONY_ERICSSON, null, 1, "Sony Ericsson", new String[] { "SonyEricsson"}, null, DeviceType.MOBILE, null ), // after symbian, some SE phones use symbian
SUN_OS( Manufacturer.SUN, null, 1, "SunOS", new String[] { "SunOS" } , null, DeviceType.COMPUTER, null ),
PSP( Manufacturer.SONY, null, 1, "Sony Playstation", new String[] { "Playstation" }, null, DeviceType.GAME_CONSOLE, null ),
/**
* Nintendo Wii game console.
*/
WII( Manufacturer.NINTENDO,null, 1, "Nintendo Wii", new String[] { "Wii" }, null, DeviceType.GAME_CONSOLE, null ),
/**
* BlackBerryOS. The BlackBerryOS exists in different version. How relevant those versions are, is not clear.
*/
BLACKBERRY( Manufacturer.BLACKBERRY,null, 1, "BlackBerryOS", new String[] { "BlackBerry" }, null, DeviceType.MOBILE, null ),
BLACKBERRY7( Manufacturer.BLACKBERRY,OperatingSystem.BLACKBERRY, 7, "BlackBerry 7", new String[] { "Version/7" }, null, DeviceType.MOBILE, null ),
BLACKBERRY6( Manufacturer.BLACKBERRY,OperatingSystem.BLACKBERRY, 6, "BlackBerry 6", new String[] { "Version/6" }, null, DeviceType.MOBILE, null ),
BLACKBERRY_TABLET(Manufacturer.BLACKBERRY,null, 100, "BlackBerry Tablet OS", new String[] { "RIM Tablet OS" }, null, DeviceType.TABLET, null ),
ROKU( Manufacturer.ROKU,null, 1, "Roku OS", new String[] { "Roku" }, null, DeviceType.DMR, null ),
/**
* Proxy server that hides the original user-agent.
* ggpht.com = Gmail proxy server
*/
PROXY( Manufacturer.OTHER,null, 10, "Proxy", new String[] { "ggpht.com" }, null, DeviceType.UNKNOWN, null ),
UNKNOWN_MOBILE( Manufacturer.OTHER,null, 3, "Unknown mobile", new String[] {"Mobile"}, null, DeviceType.MOBILE, null ),
UNKNOWN_TABLET( Manufacturer.OTHER,null, 4, "Unknown tablet", new String[] {"Tablet"}, null, DeviceType.TABLET, null ),
UNKNOWN( Manufacturer.OTHER,null, 1, "Unknown", new String[0], null, DeviceType.UNKNOWN, null );
private final short id;
private final String name;
private final String[] aliases;
private final String[] excludeList; // don't match when these values are in the agent-string
private final Manufacturer manufacturer;
private final DeviceType deviceType;
private final OperatingSystem parent;
private List<OperatingSystem> children;
private Pattern versionRegEx;
private static List<OperatingSystem> topLevelOperatingSystems;
private OperatingSystem(Manufacturer manufacturer, OperatingSystem parent, int versionId, String name,
String[] aliases,
String[] exclude, DeviceType deviceType, String versionRegexString) {
this.manufacturer = manufacturer;
this.parent = parent;
this.children = new ArrayList<OperatingSystem>();
// combine manufacturer and version id to one unique id.
this.id = (short) ((manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.aliases = Utils.toLowerCase(aliases);
this.excludeList = Utils.toLowerCase(exclude);
this.deviceType = deviceType;
if (versionRegexString != null) { // not implemented yet
this.versionRegEx = Pattern.compile(versionRegexString);
}
if (this.parent == null)
addTopLevelOperatingSystem(this);
else
this.parent.children.add(this);
}
// create collection of top level operating systems during initialization
private static void addTopLevelOperatingSystem(OperatingSystem os) {
if(topLevelOperatingSystems == null)
topLevelOperatingSystems = new ArrayList<OperatingSystem>();
topLevelOperatingSystems.add(os);
}
public short getId() {
return id;
}
public String getName() {
return name;
}
/*
* Shortcut to check of an operating system is a mobile device.
* Left in here for backwards compatibility. Use .getDeviceType() instead.
*/
@Deprecated
public boolean isMobileDevice() {
return deviceType.equals(DeviceType.MOBILE);
}
public DeviceType getDeviceType() {
return deviceType;
}
/*
* Gets the top level grouping operating system
*/
public OperatingSystem getGroup() {
if (this.parent != null) {
return parent.getGroup();
}
return this;
}
/**
* Returns the manufacturer of the operating system
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/**
* Checks if the given user-agent string matches to the operating system.
* Only checks for one specific operating system.
* @param agentString
* @return boolean
*/
public boolean isInUserAgentString(String agentString)
{
if (agentString == null) {
return false;
}
final String agentLowerCaseString = agentString.toLowerCase();
return isInUserAgentStringLowercase(agentLowerCaseString);
}
private boolean isInUserAgentStringLowercase(final String agentLowerCaseString) {
return Utils.contains(agentLowerCaseString, aliases);
}
/**
* Checks if the given user-agent does not contain one of the tokens which should not match.
* In most cases there are no excluding tokens, so the impact should be small.
* @param agentLowerCaseString
* @return
*/
private boolean containsExcludeTokenLowercase(final String agentLowerCaseString) {
return Utils.contains(agentLowerCaseString, excludeList);
}
private OperatingSystem checkUserAgentLowercase(String agentStringLowercase) {
if (this.isInUserAgentStringLowercase(agentStringLowercase)) {
if (this.children.size() > 0) {
for (OperatingSystem childOperatingSystem : this.children) {
OperatingSystem match = childOperatingSystem.checkUserAgentLowercase(agentStringLowercase);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!this.containsExcludeTokenLowercase(agentStringLowercase)) {
return this;
}
}
return null;
}
/**
* Parses user agent string and returns the best match.
* Returns OperatingSystem.UNKNOWN if there is no match.
* @param agentString
* @return OperatingSystem
*/
public static OperatingSystem parseUserAgentString(String agentString)
{
return parseUserAgentString(agentString, topLevelOperatingSystems);
}
public static OperatingSystem parseUserAgentLowercaseString(String agentString)
{
if (agentString == null) {
return OperatingSystem.UNKNOWN;
}
return parseUserAgentLowercaseString(agentString, topLevelOperatingSystems);
}
/**
* Parses the user agent string and returns the best match for the given operating systems.
* Returns OperatingSystem.UNKNOWN if there is no match.
* Be aware that if the order of the provided operating systems is incorrect or the set is too limited it can lead to false matches!
* @param agentString
* @return OperatingSystem
*/
public static OperatingSystem parseUserAgentString(String agentString, List<OperatingSystem> operatingSystems)
{
if (agentString != null) {
final String agentLowercaseString = agentString.toLowerCase();
return parseUserAgentLowercaseString(agentLowercaseString, operatingSystems);
}
return OperatingSystem.UNKNOWN;
}
private static OperatingSystem parseUserAgentLowercaseString(final String agentLowercaseString,
List<OperatingSystem> operatingSystems) {
for (OperatingSystem operatingSystem : operatingSystems)
{
OperatingSystem match = operatingSystem.checkUserAgentLowercase(agentLowercaseString);
if (match != null) {
return match; // either current operatingSystem or a child object
}
}
return OperatingSystem.UNKNOWN;
}
/**
* Returns the enum constant of this type with the specified id.
* Throws IllegalArgumentException if the value does not exist.
* @param id
* @return
*/
public static OperatingSystem valueOf(short id)
{
for (OperatingSystem operatingSystem : OperatingSystem.values())
{
if (operatingSystem.getId() == id)
return operatingSystem;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException(
"No enum const for id " + id);
}
}
|
Add new Android versions
|
src/main/java/eu/bitwalker/useragentutils/OperatingSystem.java
|
Add new Android versions
|
<ide><path>rc/main/java/eu/bitwalker/useragentutils/OperatingSystem.java
<ide> WINDOWS_MOBILE( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS, 50, "Windows Mobile", new String[] { "Windows CE" }, null, DeviceType.MOBILE, null ), // before Win
<ide> WINDOWS_98( Manufacturer.MICROSOFT,OperatingSystem.WINDOWS,5, "Windows 98", new String[] { "Windows 98","Win98" }, new String[] { "Palm" }, DeviceType.COMPUTER, null ), // before Win
<ide> XBOX_OS(Manufacturer.MICROSOFT, OperatingSystem.WINDOWS,62, "Xbox OS",new String[]{"xbox"},new String[]{}, DeviceType.GAME_CONSOLE, null),
<del>
<add>
<add> // for Google user-agent, see https://developer.chrome.com/multidevice/user-agent
<ide> ANDROID( Manufacturer.GOOGLE,null, 0, "Android", new String[] { "Android" }, new String[] {"Ubuntu"}, DeviceType.MOBILE, null ),
<del> ANDROID6( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 6, "Android 6.x", new String[] { "Android 6", "Android-6" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
<del> ANDROID6_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID6, 60, "Android 6.x Tablet", new String[] { "Android 6", "Android-6"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
<del> ANDROID5( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 5, "Android 5.x", new String[] { "Android 5", "Android-5" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
<del> ANDROID5_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID5, 50, "Android 5.x Tablet", new String[] { "Android 5", "Android-5"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
<add> ANDROID8( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 8, "Android 8.x", new String[] { "Android 8", "Android-8" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
<add> ANDROID8_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID8, 80, "Android 8.x Tablet", new String[] { "Android 8", "Android-8"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
<add> ANDROID7( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 7, "Android 7.x", new String[] { "Android 7", "Android-7" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
<add> ANDROID7_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID7, 70, "Android 7.x Tablet", new String[] { "Android 7", "Android-7"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
<add> ANDROID6( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 6, "Android 6.x", new String[] { "Android 6", "Android-6" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
<add> ANDROID6_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID6, 60, "Android 6.x Tablet", new String[] { "Android 6", "Android-6"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
<add> ANDROID5( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 5, "Android 5.x", new String[] { "Android 5", "Android-5" }, new String[] { "glass" }, DeviceType.MOBILE, null ),
<add> ANDROID5_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID5, 50, "Android 5.x Tablet", new String[] { "Android 5", "Android-5"}, new String[] { "mobile", "glass"}, DeviceType.TABLET, null ),
<ide> ANDROID4( Manufacturer.GOOGLE,OperatingSystem.ANDROID, 4, "Android 4.x", new String[] { "Android 4", "Android-4" }, new String[] { "glass", "ubuntu"}, DeviceType.MOBILE, null ),
<ide> ANDROID4_TABLET(Manufacturer.GOOGLE,OperatingSystem.ANDROID4, 40, "Android 4.x Tablet", new String[] { "Android 4", "Android-4"}, new String[] { "mobile", "glass", "ubuntu" }, DeviceType.TABLET, null ),
<ide> ANDROID4_WEARABLE(Manufacturer.GOOGLE,OperatingSystem.ANDROID, 400, "Android 4.x", new String[] { "Android 4" }, new String[] {"ubuntu"}, DeviceType.WEARABLE, null ),
|
|
Java
|
apache-2.0
|
571d1079e93f6d6f3436cff5968b72d6c769db1d
| 0 |
rancidfrog/show-java,AlanCheen/show-java,nao20010128nao/show-java,ajrulez/show-java,nrazon/show-java,thecocce/show-java,vaginessa/show-java,Shubashree/show-java,Unixcision/show-java,shinyvince/show-java,aliebrahimi1781/show-java,Ygauraw/show-java
|
package com.njlabs.showjava.ui;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.njlabs.showjava.R;
import com.njlabs.showjava.modals.DecompileHistoryItem;
import com.njlabs.showjava.utils.DatabaseHandler;
import com.njlabs.showjava.utils.picker.FileChooser;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FilenameFilter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Landing extends BaseActivity {
ProgressDialog PackageLoadDialog;
DatabaseHandler db;
List<DecompileHistoryItem> listFromDb;
private static final int FILEPICKER = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupLayout(R.layout.activity_landing);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
PackageLoadDialog = new ProgressDialog(this);
PackageLoadDialog.setIndeterminate(false);
PackageLoadDialog.setCancelable(false);
PackageLoadDialog.setInverseBackgroundForced(false);
PackageLoadDialog.setCanceledOnTouchOutside(false);
PackageLoadDialog.setMessage("Loading Decompile History ...");
//HistoryList = (ListView) findViewById(R.id.list);
db = new DatabaseHandler(this);
if(db.getHistoryItemCount()!=0)
{
//HistoryList.setVisibility(View.VISIBLE);
}
else
{
/*LinearLayout EmptyLayout=(LinearLayout) findViewById(R.id.EmptyLayout);
EmptyLayout.setVisibility(View.VISIBLE);*/
}
HistoryLoader runner = new HistoryLoader();
runner.execute();
}
private class HistoryLoader extends AsyncTask<String, String, List<DecompileHistoryItem>> {
@Override
protected List<DecompileHistoryItem> doInBackground(String... params) {
return db.getAllHistoryItems();
}
@Override
protected void onPostExecute(List<DecompileHistoryItem> AllPackages) {
// execution of result of Long time consuming operation
listFromDb = AllPackages;
SetupList(AllPackages);
PackageLoadDialog.dismiss();
ExistingHistoryLoader runner = new ExistingHistoryLoader();
runner.execute();
}
@Override
protected void onPreExecute() {
PackageLoadDialog.show();
}
@Override
protected void onProgressUpdate(String... text) {
PackageLoadDialog.setMessage(text[0]);
}
}
public void SetupList(List<DecompileHistoryItem> AllPackages)
{
ArrayAdapter<DecompileHistoryItem> aa = new ArrayAdapter<DecompileHistoryItem>(getBaseContext(), R.layout.history_list_item, AllPackages)
{
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = getLayoutInflater().inflate(R.layout.history_list_item, null);
}
DecompileHistoryItem pkg = getItem(position);
TextView PkgName = (TextView) convertView.findViewById(R.id.history_pkg_name);
TextView PkgId = (TextView) convertView.findViewById(R.id.history_pkg_id);
Typeface face=Typeface.createFromAsset(getAssets(), "roboto_light.ttf");
PkgName.setTypeface(face);
PkgId.setTypeface(face);
PkgName.setText(pkg._packagename);
PkgId.setText(pkg._packageid);
return convertView;
}
};
//setListAdapter(aa);
/*HistoryList.setAdapter(aa);
HistoryList.setTextFilterEnabled(true);
/// CREATE AN ONCLICK LISTENER TO KNOW WHEN EACH ITEM IS CLICKED
HistoryList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final TextView CPkgId=(TextView) view.findViewById(R.id.history_pkg_id);
Intent i = new Intent(getApplicationContext(), JavaExplorer.class);
File javaSourceOutputDir = new File(Environment.getExternalStorageDirectory()+"/ShowJava"+"/"+CPkgId.getText().toString()+"/java_output");
i.putExtra("java_source_dir",javaSourceOutputDir.toString()+"/");
i.putExtra("package_id",CPkgId.getText().toString());
startActivity(i);
}
});*/
}
public void OpenAppListing(View v)
{
Intent i = new Intent(getApplicationContext(), AppListing.class);
startActivity(i);
}
public void OpenFilePicker(View v)
{
Intent intent = new Intent(this, FileChooser.class);
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".apk");
intent.putStringArrayListExtra("filterFileExtension", extensions);
startActivityForResult(intent, FILEPICKER);
}
@Override
public void onResume() {
super.onResume();
if(db.getHistoryItemCount()!=0)
{
/*LinearLayout EmptyLayout=(LinearLayout) findViewById(R.id.EmptyLayout);
EmptyLayout.setVisibility(View.GONE);
HistoryList.setVisibility(View.VISIBLE);
HistoryLoader runner = new HistoryLoader();
runner.execute();*/
}
else
{
/*LinearLayout EmptyLayout=(LinearLayout) findViewById(R.id.EmptyLayout);
EmptyLayout.setVisibility(View.VISIBLE);
HistoryList.setVisibility(View.GONE);*/
}
}
private class ExistingHistoryLoader extends AsyncTask<String, String, List<DecompileHistoryItem>> {
@Override
protected List<DecompileHistoryItem> doInBackground(String... params) {
// listFromDb
File file = new File(Environment.getExternalStorageDirectory()+"/ShowJava");
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
if(directories!=null && directories.length>0) {
for (String directory : directories) {
boolean alreadyExists = false;
for (DecompileHistoryItem item : listFromDb) {
if (directory.equals(item.getPackageID())) {
Log.d("SaA", "Already Exists!!");
alreadyExists = true;
}
}
if (!alreadyExists) {
DecompileHistoryItem newItem = new DecompileHistoryItem(directory, directory, DateFormat.getDateInstance().format(new Date()));
db.addHistoryItem(newItem);
listFromDb.add(newItem);
}
}
}
return listFromDb;
}
@Override
protected void onPostExecute(List<DecompileHistoryItem> AllPackages) {
// execution of result of Long time consuming operation
SetupList(AllPackages);
}
@Override
protected void onPreExecute() {
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILEPICKER) {
if (data != null) {
String PackageDir = data.getStringExtra("fileSelected");
//Toast.makeText(this, fileSelected, Toast.LENGTH_SHORT).show();
String PackageName;
String PackageId;
if(FilenameUtils.isExtension(PackageDir, "apk"))
{
PackageManager pm = getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(PackageDir, PackageManager.GET_ACTIVITIES);
if(info != null){
ApplicationInfo appInfo = info.applicationInfo;
if(Build.VERSION.SDK_INT >= 8){
appInfo.sourceDir = PackageDir;
appInfo.publicSourceDir = PackageDir;
}
PackageName = info.applicationInfo.loadLabel(getPackageManager()).toString();
PackageId = info.packageName;
} else {
PackageName = "";
PackageId = "";
}
}
else
{
PackageName=FilenameUtils.getName(PackageDir);
PackageId=FilenameUtils.getName(PackageDir).replaceAll(" ", "_").toLowerCase();
}
Intent i = new Intent(getApplicationContext(), AppProcessActivity.class);
i.putExtra("package_id",PackageId);
i.putExtra("package_label",PackageName);
i.putExtra("package_file_path",PackageDir);
startActivity(i);
}
}
}
}
|
app/src/main/java/com/njlabs/showjava/ui/Landing.java
|
package com.njlabs.showjava.ui;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.njlabs.showjava.R;
import com.njlabs.showjava.modals.DecompileHistoryItem;
import com.njlabs.showjava.utils.DatabaseHandler;
import com.njlabs.showjava.utils.picker.FileChooser;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FilenameFilter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Landing extends BaseActivity {
ProgressDialog PackageLoadDialog;
DatabaseHandler db;
List<DecompileHistoryItem> listFromDb;
private static final int FILEPICKER = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupLayout(R.layout.activity_landing);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
PackageLoadDialog = new ProgressDialog(this);
PackageLoadDialog.setIndeterminate(false);
PackageLoadDialog.setCancelable(false);
PackageLoadDialog.setInverseBackgroundForced(false);
PackageLoadDialog.setCanceledOnTouchOutside(false);
PackageLoadDialog.setMessage("Loading Decompile History ...");
//HistoryList = (ListView) findViewById(R.id.list);
db = new DatabaseHandler(this);
if(db.getHistoryItemCount()!=0)
{
//HistoryList.setVisibility(View.VISIBLE);
}
else
{
/*LinearLayout EmptyLayout=(LinearLayout) findViewById(R.id.EmptyLayout);
EmptyLayout.setVisibility(View.VISIBLE);*/
}
HistoryLoader runner = new HistoryLoader();
runner.execute();
}
private class HistoryLoader extends AsyncTask<String, String, List<DecompileHistoryItem>> {
@Override
protected List<DecompileHistoryItem> doInBackground(String... params) {
return db.getAllHistoryItems();
}
@Override
protected void onPostExecute(List<DecompileHistoryItem> AllPackages) {
// execution of result of Long time consuming operation
listFromDb = AllPackages;
SetupList(AllPackages);
PackageLoadDialog.dismiss();
ExistingHistoryLoader runner = new ExistingHistoryLoader();
runner.execute();
}
@Override
protected void onPreExecute() {
PackageLoadDialog.show();
}
@Override
protected void onProgressUpdate(String... text) {
PackageLoadDialog.setMessage(text[0]);
}
}
public void SetupList(List<DecompileHistoryItem> AllPackages)
{
ArrayAdapter<DecompileHistoryItem> aa = new ArrayAdapter<DecompileHistoryItem>(getBaseContext(), R.layout.history_list_item, AllPackages)
{
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = getLayoutInflater().inflate(R.layout.history_list_item, null);
}
DecompileHistoryItem pkg = getItem(position);
TextView PkgName = (TextView) convertView.findViewById(R.id.history_pkg_name);
TextView PkgId = (TextView) convertView.findViewById(R.id.history_pkg_id);
Typeface face=Typeface.createFromAsset(getAssets(), "roboto_light.ttf");
PkgName.setTypeface(face);
PkgId.setTypeface(face);
PkgName.setText(pkg._packagename);
PkgId.setText(pkg._packageid);
return convertView;
}
};
//setListAdapter(aa);
/*HistoryList.setAdapter(aa);
HistoryList.setTextFilterEnabled(true);
/// CREATE AN ONCLICK LISTENER TO KNOW WHEN EACH ITEM IS CLICKED
HistoryList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final TextView CPkgId=(TextView) view.findViewById(R.id.history_pkg_id);
Intent i = new Intent(getApplicationContext(), JavaExplorer.class);
File javaSourceOutputDir = new File(Environment.getExternalStorageDirectory()+"/ShowJava"+"/"+CPkgId.getText().toString()+"/java_output");
i.putExtra("java_source_dir",javaSourceOutputDir.toString()+"/");
i.putExtra("package_id",CPkgId.getText().toString());
startActivity(i);
}
});*/
}
public void OpenAppListing(View v)
{
Intent i = new Intent(getApplicationContext(), AppListing.class);
startActivity(i);
}
public void OpenFilePicker(View v)
{
Intent intent = new Intent(this, FileChooser.class);
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".apk");
intent.putStringArrayListExtra("filterFileExtension", extensions);
startActivityForResult(intent, FILEPICKER);
}
@Override
public void onResume() {
super.onResume();
if(db.getHistoryItemCount()!=0)
{
/*LinearLayout EmptyLayout=(LinearLayout) findViewById(R.id.EmptyLayout);
EmptyLayout.setVisibility(View.GONE);
HistoryList.setVisibility(View.VISIBLE);
HistoryLoader runner = new HistoryLoader();
runner.execute();*/
}
else
{
/*LinearLayout EmptyLayout=(LinearLayout) findViewById(R.id.EmptyLayout);
EmptyLayout.setVisibility(View.VISIBLE);
HistoryList.setVisibility(View.GONE);*/
}
}
private class ExistingHistoryLoader extends AsyncTask<String, String, List<DecompileHistoryItem>> {
@Override
protected List<DecompileHistoryItem> doInBackground(String... params) {
// listFromDb
File file = new File(Environment.getExternalStorageDirectory()+"/ShowJava");
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
if(directories!=null && directories.length>0) {
for (String directory : directories) {
boolean alreadyExists = false;
for (DecompileHistoryItem item : listFromDb) {
if (directory.equals(item.getPackageID())) {
Log.d("SaA", "Already Exists!!");
alreadyExists = true;
}
}
if (alreadyExists == false) {
DecompileHistoryItem newItem = new DecompileHistoryItem(directory, directory, DateFormat.getDateInstance().format(new Date()));
db.addHistoryItem(newItem);
listFromDb.add(newItem);
}
}
}
return listFromDb;
}
@Override
protected void onPostExecute(List<DecompileHistoryItem> AllPackages) {
// execution of result of Long time consuming operation
SetupList(AllPackages);
}
@Override
protected void onPreExecute() {
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILEPICKER) {
if (data != null) {
String fileSelected = data.getStringExtra("fileSelected");
//Toast.makeText(this, fileSelected, Toast.LENGTH_SHORT).show();
String PackageDir = fileSelected;
String PackageName;
String PackageId;
if(FilenameUtils.isExtension(PackageDir, "apk"))
{
PackageManager pm = getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(PackageDir, PackageManager.GET_ACTIVITIES);
if(info != null){
ApplicationInfo appInfo = info.applicationInfo;
if(Build.VERSION.SDK_INT >= 8){
appInfo.sourceDir = PackageDir;
appInfo.publicSourceDir = PackageDir;
}
}
PackageName = info.applicationInfo.loadLabel(getPackageManager()).toString();
PackageId = info.packageName;
}
else
{
PackageName=FilenameUtils.getName(PackageDir);
PackageId=FilenameUtils.getName(PackageDir).replaceAll(" ", "_").toLowerCase();
}
Intent i = new Intent(getApplicationContext(), AppProcessActivity.class);
i.putExtra("package_id",PackageId);
i.putExtra("package_name",PackageName);
i.putExtra("package_dir",PackageDir);
startActivity(i);
}
}
}
}
|
Fixed a refactor I overlooked (thanks to https://github.com/eyecatchup/)
|
app/src/main/java/com/njlabs/showjava/ui/Landing.java
|
Fixed a refactor I overlooked (thanks to https://github.com/eyecatchup/)
|
<ide><path>pp/src/main/java/com/njlabs/showjava/ui/Landing.java
<ide> alreadyExists = true;
<ide> }
<ide> }
<del>
<del> if (alreadyExists == false) {
<add> if (!alreadyExists) {
<ide> DecompileHistoryItem newItem = new DecompileHistoryItem(directory, directory, DateFormat.getDateInstance().format(new Date()));
<ide> db.addHistoryItem(newItem);
<ide> listFromDb.add(newItem);
<ide> public void onActivityResult(int requestCode, int resultCode, Intent data) {
<ide> if (requestCode == FILEPICKER) {
<ide> if (data != null) {
<del> String fileSelected = data.getStringExtra("fileSelected");
<add> String PackageDir = data.getStringExtra("fileSelected");
<ide> //Toast.makeText(this, fileSelected, Toast.LENGTH_SHORT).show();
<del> String PackageDir = fileSelected;
<ide> String PackageName;
<ide> String PackageId;
<ide>
<ide> appInfo.sourceDir = PackageDir;
<ide> appInfo.publicSourceDir = PackageDir;
<ide> }
<add> PackageName = info.applicationInfo.loadLabel(getPackageManager()).toString();
<add> PackageId = info.packageName;
<add>
<add> } else {
<add> PackageName = "";
<add> PackageId = "";
<ide> }
<del> PackageName = info.applicationInfo.loadLabel(getPackageManager()).toString();
<del> PackageId = info.packageName;
<ide> }
<ide> else
<ide> {
<ide>
<ide> Intent i = new Intent(getApplicationContext(), AppProcessActivity.class);
<ide> i.putExtra("package_id",PackageId);
<del> i.putExtra("package_name",PackageName);
<del> i.putExtra("package_dir",PackageDir);
<add> i.putExtra("package_label",PackageName);
<add> i.putExtra("package_file_path",PackageDir);
<ide> startActivity(i);
<ide>
<ide> }
|
|
JavaScript
|
mit
|
c4eb4a417ea4e4984e68dd880290bf39c9d6060f
| 0 |
joemcmahon/mrspiral-spudbot
|
'use strict'
const Slapp = require('slapp')
const Context = require('./context')
const ConvoStore = require('./convo-store')
const YAML = require('js-yaml')
const fs = require('fs')
const _ = require('lodash')
const handleHowAreYou = 'handleHowAreYou'
const handleSweetDreams = 'handleSweetDreams'
module.exports = (server, db) => {
console.log('initializing Slapp')
let app = Slapp({
verify_token: process.env.SLACK_VERIFY_TOKEN,
context: Context(db),
convo_store: ConvoStore(db)
})
var Monitor = require('icecast-monitor');
var monitor = new Monitor({
host: 'radio.radiospiral.net',
port: 8000,
user: process.env.RADIO_USER,
password: process.env.RADIO_PASSWORD,
});
// Load oblique strategies
var strategies;
try {
strategies = YAML.safeLoad(fs.readFileSync('strategies.yml', 'utf8'));
console.log(strategies[0]);
} catch(e) {
console.log("Failed to load Oblique Strategies: " + e);
}
var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`track\` - to see what the current track is.
\`peak\` - report on the peak listener count.
\`history\` - to get a list of previously played tracks.
\`strategy\` - to get a random Oblique Strategy.
I am very polite as well.
`
// *********************************************
// Setup different handlers for messages
// *********************************************
const stopper = `I wasn't listening...`
var previousTrack = `Nil`
var currentTrack = stopper
var testTrack = `Nol`
var numListeners = 0
var trackHistory = []
var numTracks = 0
var maxTracks = 10
var histIndex = 0
monitor.createFeed(function(err, feed) {
if (err) throw err;
// Handle wildcard events
//feed.on('*', function(event, data, raw) {
// console.log(event, data, raw);
// });
// Handle listener change
feed.on('mount.listeners', function(listeners, raw) {
numListeners = raw;
console.log(listeners, raw);
});
// Handle track title change here
feed.on('mount.title', function(title, track) {
console.log('Now playing: ' + track); // for debugging right now. should mean the track has changed
testTrack = track; // not sure what type track is, so force it to a string
if (currentTrack !== testTrack) {
//console.log(currentTrack + " is not equal to " + testTrack); // debug, they aren't equal, so yes
numTracks = numTracks + 1; // to set a limit on history size we have to count tracks
previousTrack = currentTrack; // save the no longer current track as the previous
currentTrack = track; // now store the current track
trackHistory = _.concat(trackHistory,previousTrack); // save previous track
if (numTracks > maxTracks) {
trackHistory = _.drop(trackHistory);
numTracks = maxTracks;
}
} else {
console.log('**dupEvent ' + currentTrack + ' is equal to ' + testTrack);
}
console.log('previous: ' + previousTrack); //debugging some more here
histIndex = numTracks;
while (histIndex > 0) {
console.log('track history: ' + trackHistory[histIndex]); //works, backwards I think
histIndex = histIndex - 1;
}
// slapp.use((track, next) => {
// console.log(track)
// msg.say('Now playing: ' + track);
// next()
// })
// message.say('Now playing: ' + track);
});
});
// handle changed messages (don't know what to do with this yet)
//slapp.event('message_changed', (msg) => {
// let token = msg.meta.bot_token
// let id = msg.body.event.item.ts
// let channel = msg.body.event.item.channel
// slapp.client.reactions.add({token, 'smile', id, channel}, (err) => {
// if (err) console.log('Error adding reaction', err)
// })
//})
app
.event('url_verification', (msg) => {
//parse for the challenge element and return its value
msg.respond(msg.challenge, (err) => {})
})
.message(/oblique|strateg(y|ies)/i, ['mention', 'direct_message'], (msg) => {
msg.say(_.sample(strategies))
})
.message(/track|playing|hearing|tune|listening|music/i, ['mention', 'direct_message'], (msg) => {
msg.say('Now playing: ' + currentTrack + ' (' + numListeners + ' listening)');
msg.say('Previous: ' + previousTrack);
})
.message(/history|played/i, ['mention', 'direct_message'], (msg) => {
histIndex = numTracks;
if (trackHistory === null) {
trackHistory = [stopper]
}
if (trackHistory.length === 1 && trackHistory[0] === stopper && currentTrack !== null) {
trackHistory = [currentTrack]
}
if (trackHistory > 0) {
if (currentTrack != null && _.last(trackHistory) != currentTrack) {
trackHistory = _.concat(trackHistory, currentTrack)
}
}
console.log(trackHistory)
var sawNonStopper = false
var first = true
msg.say('What has played recently:')
_.eachRight(trackHistory, function(value) {
if (value !== stopper) {
sawNonStopper = true
if (first) {
value = value + " (now playing)"
first = false
}
msg.say(value)
} else {
if (!sawNonStopper) {
msg.say(value)
return
}
}
})
})
.message(/(T|t)hank( |s|y|ies)|cheers|ty/i, ['mention', 'direct_message'], (msg) => {
if (Math.random() < 0.98) {
msg.say(['No problem!', 'You are welcome!', 'Happy to help!', 'de nada!', 'My pleasure!', ':pray:', ':raised_hands:', 'cool'])
}
})
.message('help', ['mention', 'direct_mention', 'direct_message'], (msg, text) => {
msg.say(HELP_TEXT)
})
// Catch-all for any other responses not handled above
.message('.*', ['mention', 'direct_mention', 'direct_message'], (msg) => {
// respond 90% of the time
if (Math.random() < 0.9) {
msg.say([
':wave:',
':pray:',
':raised_hands:',
'Word.',
':wink:',
'Did you say something?',
':innocent:',
':hankey:',
':smirk:',
':stuck_out_tongue:',
':sparkles:',
':punch:',
':boom:',
':smiling imp:',
':neckbeard:'
])
}
})
.attachToExpress(server)
return app
}
|
lib/slapp.js
|
'use strict'
const Slapp = require('slapp')
const Context = require('./context')
const ConvoStore = require('./convo-store')
const YAML = require('js-yaml')
const fs = require('fs')
const _ = require('lodash')
const handleHowAreYou = 'handleHowAreYou'
const handleSweetDreams = 'handleSweetDreams'
module.exports = (server, db) => {
console.log('initializing Slapp')
let app = Slapp({
verify_token: process.env.SLACK_VERIFY_TOKEN,
context: Context(db),
convo_store: ConvoStore(db)
})
var Monitor = require('icecast-monitor');
var monitor = new Monitor({
host: 'radio.radiospiral.net',
port: 8000,
user: process.env.RADIO_USER,
password: process.env.RADIO_PASSWORD,
});
// Load oblique strategies
var strategies;
try {
strategies = YAML.safeLoad(fs.readFileSync('strategies.yml', 'utf8'));
console.log(strategies[0]);
} catch(e) {
console.log("Failed to load Oblique Strategies: " + e);
}
var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`track\` - to see what the current track is.
\`peak\` - report on the peak listener count.
\`history\` - to get a list of previously played tracks.
\`strategy\` - to get a random Oblique Strategy.
I am very polite as well.
`
// *********************************************
// Setup different handlers for messages
// *********************************************
const stopper = `I wasn't listening...`
var previousTrack = `Nil`
var currentTrack = stopper
var testTrack = `Nol`
var numListeners = 0
var trackHistory = []
var numTracks = 0
var maxTracks = 10
var histIndex = 0
monitor.createFeed(function(err, feed) {
if (err) throw err;
// Handle wildcard events
//feed.on('*', function(event, data, raw) {
// console.log(event, data, raw);
// });
// Handle listener change
feed.on('mount.listeners', function(listeners, raw) {
numListeners = raw;
console.log(listeners, raw);
});
// Handle track title change here
feed.on('mount.title', function(title, track) {
console.log('Now playing: ' + track); // for debugging right now. should mean the track has changed
testTrack = track; // not sure what type track is, so force it to a string
if (currentTrack !== testTrack) {
//console.log(currentTrack + " is not equal to " + testTrack); // debug, they aren't equal, so yes
numTracks = numTracks + 1; // to set a limit on history size we have to count tracks
previousTrack = currentTrack; // save the no longer current track as the previous
currentTrack = track; // now store the current track
trackHistory = _.concat(trackHistory,previousTrack); // save previous track
if (numTracks > maxTracks) {
trackHistory = _.drop(trackHistory);
numTracks = maxTracks;
}
} else {
console.log('**dupEvent ' + currentTrack + ' is equal to ' + testTrack);
}
console.log('previous: ' + previousTrack); //debugging some more here
histIndex = numTracks;
while (histIndex > 0) {
console.log('track history: ' + trackHistory[histIndex]); //works, backwards I think
histIndex = histIndex - 1;
}
// slapp.use((track, next) => {
// console.log(track)
// msg.say('Now playing: ' + track);
// next()
// })
// message.say('Now playing: ' + track);
});
});
// handle changed messages (don't know what to do with this yet)
//slapp.event('message_changed', (msg) => {
// let token = msg.meta.bot_token
// let id = msg.body.event.item.ts
// let channel = msg.body.event.item.channel
// slapp.client.reactions.add({token, 'smile', id, channel}, (err) => {
// if (err) console.log('Error adding reaction', err)
// })
//})
app
.event('url_verification', (msg) => {
//parse for the challenge element and return its value
msg.respond(msg.challenge, (err) => {})
})
.message(/oblique|strateg(y|ies)/i, ['mention', 'direct_message'], (msg) => {
msg.say(_.sample(strategies))
})
.message(/track|playing|hearing|tune|listening|music/i, ['mention', 'direct_message'], (msg) => {
msg.say('Now playing: ' + currentTrack + ' (' + numListeners + ' listening)');
msg.say('Previous: ' + previousTrack);
})
.message(/(T|t)hank( |s|y|ies)|cheers|ty/i, ['mention', 'direct_message'], (msg) => {
if (Math.random() < 0.98) {
msg.say(['No problem!', 'You are welcome!', 'Happy to help!', 'de nada!', 'My pleasure!', ':pray:', ':raised_hands:', 'cool'])
}
})
.message('help', ['mention', 'direct_mention', 'direct_message'], (msg, text) => {
msg.say(HELP_TEXT)
})
// Catch-all for any other responses not handled above
.message('.*', ['mention', 'direct_mention', 'direct_message'], (msg) => {
// respond 90% of the time
if (Math.random() < 0.9) {
msg.say([
':wave:',
':pray:',
':raised_hands:',
'Word.',
':wink:',
'Did you say something?',
':innocent:',
':hankey:',
':smirk:',
':stuck_out_tongue:',
':sparkles:',
':punch:',
':boom:',
':smiling imp:',
':neckbeard:'
])
}
})
.attachToExpress(server)
return app
}
|
Restore track history command
|
lib/slapp.js
|
Restore track history command
|
<ide><path>ib/slapp.js
<ide> msg.say('Now playing: ' + currentTrack + ' (' + numListeners + ' listening)');
<ide> msg.say('Previous: ' + previousTrack);
<ide> })
<del>
<add> .message(/history|played/i, ['mention', 'direct_message'], (msg) => {
<add>
<add> histIndex = numTracks;
<add> if (trackHistory === null) {
<add> trackHistory = [stopper]
<add> }
<add> if (trackHistory.length === 1 && trackHistory[0] === stopper && currentTrack !== null) {
<add> trackHistory = [currentTrack]
<add> }
<add> if (trackHistory > 0) {
<add> if (currentTrack != null && _.last(trackHistory) != currentTrack) {
<add> trackHistory = _.concat(trackHistory, currentTrack)
<add> }
<add> }
<add> console.log(trackHistory)
<add> var sawNonStopper = false
<add> var first = true
<add> msg.say('What has played recently:')
<add> _.eachRight(trackHistory, function(value) {
<add> if (value !== stopper) {
<add> sawNonStopper = true
<add> if (first) {
<add> value = value + " (now playing)"
<add> first = false
<add> }
<add> msg.say(value)
<add> } else {
<add> if (!sawNonStopper) {
<add> msg.say(value)
<add> return
<add> }
<add> }
<add> })
<add> })
<ide> .message(/(T|t)hank( |s|y|ies)|cheers|ty/i, ['mention', 'direct_message'], (msg) => {
<ide> if (Math.random() < 0.98) {
<ide> msg.say(['No problem!', 'You are welcome!', 'Happy to help!', 'de nada!', 'My pleasure!', ':pray:', ':raised_hands:', 'cool'])
|
|
Java
|
mit
|
3b95a0034e99a4852ac97a0089cd11adfd7843c2
| 0 |
opennars/opennars,opennars/opennars,opennars/opennars,opennars/opennars
|
/*
* Here comes the text of your license
* Each line should be prefixed with *
*/
package nars.plugin.mental;
import nars.core.EventEmitter;
import nars.core.NAR;
import nars.core.Parameters;
import nars.core.Plugin;
/**
*
* @author tc
*/
public class RuntimeNARSettings implements Plugin {
NAR n=null;
@Override
public boolean setEnabled(NAR n, boolean enabled) {
this.n=n;
return true;
}
public boolean isImmediateEternalization() {
return Parameters.IMMEDIATE_ETERNALIZATION;
}
public void setImmediateEternalization(boolean val) {
Parameters.IMMEDIATE_ETERNALIZATION=val;
}
public double getDuration() {
return n.param.duration.get();
}
public void setDuration(double val) {
n.param.duration.set((int) val);
}
public double getDerivationPriorityLeak() {
return Parameters.DERIVATION_PRIORITY_LEAK;
}
public void setDerivationPriorityLeak(double val) {
Parameters.DERIVATION_PRIORITY_LEAK=(float) val;
}
public double getDerivationDurabilityLeak() {
return Parameters.DERIVATION_DURABILITY_LEAK;
}
public void setDerivationDurabilityLeak(double val) {
Parameters.DERIVATION_DURABILITY_LEAK=(float) val;
}
public double getTemporalInductionPriority() {
return Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES;
}
public void setTemporalInductionPriority(double val) {
Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES=(int) val;
}
public double getEvidentalHorizon() {
return Parameters.HORIZON;
}
public void setEvidentalHorizon(double val) {
Parameters.HORIZON=(float) val;
}
public boolean isInductionOnSucceedingEvents() {
return Parameters.TEMPORAL_INDUCTION_ON_SUCCEEDING_EVENTS;
}
public void setInductionOnSucceedingEvents(boolean val) {
Parameters.TEMPORAL_INDUCTION_ON_SUCCEEDING_EVENTS=val;
}
public double getInductionChainSamples() {
return Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES;
}
public void setInductionChainSamples(double val) {
Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES=(int) val;
}
public double getInductionSamples() {
return Parameters.TEMPORAL_INDUCTION_SAMPLES;
}
public void setInductionSamples(double val) {
Parameters.TEMPORAL_INDUCTION_SAMPLES=(int) val;
}
public double getCuriosityDesireConfidenceMul() {
return Parameters.CURIOSITY_DESIRE_CONFIDENCE_MUL;
}
public void setCuriosityDesireConfidenceMul(double val) {
Parameters.CURIOSITY_DESIRE_CONFIDENCE_MUL=(float) val;
}
public double getCuriosityDesirePriorityMul() {
return Parameters.CURIOSITY_DESIRE_PRIORITY_MUL;
}
public void setCuriosityDesirePriorityMul(double val) {
Parameters.CURIOSITY_DESIRE_PRIORITY_MUL=(float)val;
}
public double getCuriosityDesireDurabilityMul() {
return Parameters.CURIOSITY_DESIRE_DURABILITY_MUL;
}
public void setCuriosityDesireDurabilityMul(double val) {
Parameters.CURIOSITY_DESIRE_DURABILITY_MUL=(float) val;
}
public boolean isCuriosityForOperatorOnly() {
return Parameters.CURIOSITY_FOR_OPERATOR_ONLY;
}
public void setCuriosityForOperatorOnly(boolean val) {
Parameters.CURIOSITY_FOR_OPERATOR_ONLY=val;
}
public double getHappyEventHigherThreshold() {
return Parameters.HAPPY_EVENT_HIGHER_THRESHOLD;
}
public void setHappyEventHigherThreshold(double val) {
Parameters.HAPPY_EVENT_HIGHER_THRESHOLD=(float) val;
}
public double getHappyEventLowerThreshold() {
return Parameters.HAPPY_EVENT_LOWER_THRESHOLD;
}
public void setHappyEventLowerThreshold(double val) {
Parameters.HAPPY_EVENT_LOWER_THRESHOLD=(float) val;
}
/* public double getBusyEventHigherThreshold() {
return Parameters.BUSY_EVENT_HIGHER_THRESHOLD;
}
public void setBusyEventHigherThreshold(double val) {
Parameters.BUSY_EVENT_HIGHER_THRESHOLD=(float) val;
}
public double getBusyEventLowerThreshold() {
return Parameters.BUSY_EVENT_LOWER_THRESHOLD;
}
public void setBusyEventLowerThreshold(double val) {
Parameters.BUSY_EVENT_LOWER_THRESHOLD=(float) val;
}*/
public boolean isReflectMetaHappyGoal() {
return Parameters.REFLECT_META_HAPPY_GOAL;
}
public void setReflectMetaHappyGoal(boolean val) {
Parameters.REFLECT_META_HAPPY_GOAL=val;
}
public boolean isUsingConsiderRemind() {
return Parameters.CONSIDER_REMIND;
}
public void setUsingConsiderRemind(boolean val) {
Parameters.CONSIDER_REMIND=val;
}
public boolean isQuestionGenerationOnDecisionMaking() {
return Parameters.QUESTION_GENERATION_ON_DECISION_MAKING;
}
public void setQuestionGenerationOnDecisionMaking(boolean val) {
Parameters.QUESTION_GENERATION_ON_DECISION_MAKING=val;
}
public boolean isCuriosityAlsoOnLowConfidentHighPriorityBelief() {
return Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF;
}
public void setCuriosityAlsoOnLowConfidentHighPriorityBelief(boolean val) {
Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF=val;
}
public double getCuriosityPriorityThreshold() {
return Parameters.CURIOSITY_PRIORITY_THRESHOLD;
}
public void setCuriosityPriorityThreshold(double val) {
Parameters.CURIOSITY_PRIORITY_THRESHOLD=(float) val;
}
public double getCuriosityConfidenceThreshold() {
return Parameters.CURIOSITY_CONFIDENCE_THRESHOLD;
}
public void setCuriosityConfidenceThreshold(double val) {
Parameters.CURIOSITY_CONFIDENCE_THRESHOLD=(float) val;
}
}
|
nars_java/nars/plugin/mental/RuntimeNARSettings.java
|
/*
* Here comes the text of your license
* Each line should be prefixed with *
*/
package nars.plugin.mental;
import nars.core.EventEmitter;
import nars.core.NAR;
import nars.core.Parameters;
import nars.core.Plugin;
/**
*
* @author tc
*/
public class RuntimeNARSettings implements Plugin {
NAR n=null;
@Override
public boolean setEnabled(NAR n, boolean enabled) {
this.n=n;
return true;
}
public boolean isImmediateEternalization() {
return Parameters.IMMEDIATE_ETERNALIZATION;
}
public void setImmediateEternalization(boolean val) {
Parameters.IMMEDIATE_ETERNALIZATION=val;
}
public double getDuration() {
return n.param.duration.get();
}
public void setDuration(double val) {
n.param.duration.set((int) val);
}
public double getDerivationPriorityLeak() {
return Parameters.DERIVATION_PRIORITY_LEAK;
}
public void setDerivationPriorityLeak(double val) {
Parameters.DERIVATION_PRIORITY_LEAK=(float) val;
}
public double getDerivationDurabilityLeak() {
return Parameters.DERIVATION_DURABILITY_LEAK;
}
public void setDerivationDurabilityLeak(double val) {
Parameters.DERIVATION_DURABILITY_LEAK=(float) val;
}
public double getTemporalInductionPriority() {
return Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES;
}
public void setTemporalInductionPriority(double val) {
Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES=(int) val;
}
public double getEvidentalHorizon() {
return Parameters.HORIZON;
}
public void setEvidentalHorizon(double val) {
Parameters.HORIZON=(float) val;
}
public boolean isInductionOnSucceedingEvents() {
return Parameters.TEMPORAL_INDUCTION_ON_SUCCEEDING_EVENTS;
}
public void setInductionOnSucceedingEvents(boolean val) {
Parameters.TEMPORAL_INDUCTION_ON_SUCCEEDING_EVENTS=val;
}
public double getInductionChainSamples() {
return Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES;
}
public void setInductionChainSamples(double val) {
Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES=(int) val;
}
public double getInductionSamples() {
return Parameters.TEMPORAL_INDUCTION_SAMPLES;
}
public void setInductionSamples(double val) {
Parameters.TEMPORAL_INDUCTION_SAMPLES=(int) val;
}
public double getCuriosityDesireConfidenceMul() {
return Parameters.CURIOSITY_DESIRE_CONFIDENCE_MUL;
}
public void setCuriosityDesireConfidenceMul(double val) {
Parameters.CURIOSITY_DESIRE_CONFIDENCE_MUL=(float) val;
}
public double getCuriosityDesirePriorityMul() {
return Parameters.CURIOSITY_DESIRE_PRIORITY_MUL;
}
public void setCuriosityDesirePriorityMul(double val) {
Parameters.CURIOSITY_DESIRE_PRIORITY_MUL=(float)val;
}
public double getCuriosityDesireDurabilityMul() {
return Parameters.CURIOSITY_DESIRE_DURABILITY_MUL;
}
public void setCuriosityDesireDurabilityMul(double val) {
Parameters.CURIOSITY_DESIRE_DURABILITY_MUL=(float) val;
}
public boolean isCuriosityForOperatorOnly() {
return Parameters.CURIOSITY_FOR_OPERATOR_ONLY;
}
public void setCuriosityForOperatorOnly(boolean val) {
Parameters.CURIOSITY_FOR_OPERATOR_ONLY=val;
}
public double getHappyEventHigherThreshold() {
return Parameters.HAPPY_EVENT_HIGHER_THRESHOLD;
}
public void setHappyEventHigherThreshold(double val) {
Parameters.HAPPY_EVENT_HIGHER_THRESHOLD=(float) val;
}
public double getHappyEventLowerThreshold() {
return Parameters.HAPPY_EVENT_LOWER_THRESHOLD;
}
public void setHappyEventLowerThreshold(double val) {
Parameters.HAPPY_EVENT_LOWER_THRESHOLD=(float) val;
}
/* public double getBusyEventHigherThreshold() {
return Parameters.BUSY_EVENT_HIGHER_THRESHOLD;
}
public void setBusyEventHigherThreshold(double val) {
Parameters.BUSY_EVENT_HIGHER_THRESHOLD=(float) val;
}
public double getBusyEventLowerThreshold() {
return Parameters.BUSY_EVENT_LOWER_THRESHOLD;
}
public void setBusyEventLowerThreshold(double val) {
Parameters.BUSY_EVENT_LOWER_THRESHOLD=(float) val;
}*/
public boolean isReflectMetaHappyGoal() {
return Parameters.REFLECT_META_HAPPY_GOAL;
}
public void setReflectMetaHappyGoal(boolean val) {
Parameters.REFLECT_META_HAPPY_GOAL=val;
}
public boolean isCuriosityAlsoOnLowConfidentHighPriorityBelief() {
return Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF;
}
public void setCuriosityAlsoOnLowConfidentHighPriorityBelief(boolean val) {
Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF=val;
}
public double getCuriosityPriorityThreshold() {
return Parameters.CURIOSITY_PRIORITY_THRESHOLD;
}
public void setCuriosityPriorityThreshold(double val) {
Parameters.CURIOSITY_PRIORITY_THRESHOLD=(float) val;
}
public double getCuriosityConfidenceThreshold() {
return Parameters.CURIOSITY_CONFIDENCE_THRESHOLD;
}
public void setCuriosityConfidenceThreshold(double val) {
Parameters.CURIOSITY_CONFIDENCE_THRESHOLD=(float) val;
}
}
|
settings reveiling.
|
nars_java/nars/plugin/mental/RuntimeNARSettings.java
|
settings reveiling.
|
<ide><path>ars_java/nars/plugin/mental/RuntimeNARSettings.java
<ide> public void setReflectMetaHappyGoal(boolean val) {
<ide> Parameters.REFLECT_META_HAPPY_GOAL=val;
<ide> }
<del>
<add>
<add> public boolean isUsingConsiderRemind() {
<add> return Parameters.CONSIDER_REMIND;
<add> }
<add> public void setUsingConsiderRemind(boolean val) {
<add> Parameters.CONSIDER_REMIND=val;
<add> }
<add>
<add> public boolean isQuestionGenerationOnDecisionMaking() {
<add> return Parameters.QUESTION_GENERATION_ON_DECISION_MAKING;
<add> }
<add> public void setQuestionGenerationOnDecisionMaking(boolean val) {
<add> Parameters.QUESTION_GENERATION_ON_DECISION_MAKING=val;
<add> }
<add>
<ide> public boolean isCuriosityAlsoOnLowConfidentHighPriorityBelief() {
<ide> return Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF;
<ide> }
|
|
Java
|
bsd-3-clause
|
115891c25cb0764f84b66432c3925fe787836028
| 0 |
harnesscloud/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,jswrenn/xtreemfs,harnesscloud/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,kleingeist/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs,jswrenn/xtreemfs,kleingeist/xtreemfs,harnesscloud/xtreemfs,harnesscloud/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,kleingeist/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs,rbaerzib/xtreemfs,kleingeist/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,kleingeist/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,kleingeist/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs,jswrenn/xtreemfs,jswrenn/xtreemfs
|
package org.xtreemfs.test.common.benchmark;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.xtreemfs.common.benchmark.BenchmarkUtils.KiB_IN_BYTES;
import static org.xtreemfs.common.benchmark.BenchmarkUtils.MiB_IN_BYTES;
import static org.xtreemfs.foundation.pbrpc.client.RPCAuthentication.authNone;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.xtreemfs.common.benchmark.BenchmarkConfig;
import org.xtreemfs.common.benchmark.BenchmarkConfig.ConfigBuilder;
import org.xtreemfs.common.benchmark.BenchmarkResult;
import org.xtreemfs.common.benchmark.BenchmarkUtils;
import org.xtreemfs.common.benchmark.BenchmarkUtils.BenchmarkType;
import org.xtreemfs.common.benchmark.Controller;
import org.xtreemfs.common.libxtreemfs.Client;
import org.xtreemfs.common.libxtreemfs.ClientFactory;
import org.xtreemfs.common.libxtreemfs.Options;
import org.xtreemfs.common.libxtreemfs.Volume;
import org.xtreemfs.common.libxtreemfs.exceptions.VolumeNotFoundException;
import org.xtreemfs.dir.DIRClient;
import org.xtreemfs.dir.DIRConfig;
import org.xtreemfs.dir.DIRRequestDispatcher;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC;
import org.xtreemfs.foundation.util.FSUtils;
import org.xtreemfs.mrc.MRCRequestDispatcher;
import org.xtreemfs.osd.OSD;
import org.xtreemfs.osd.OSDConfig;
import org.xtreemfs.pbrpc.generatedinterfaces.DIRServiceClient;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes;
import org.xtreemfs.test.SetupUtils;
import org.xtreemfs.test.TestEnvironment;
import org.xtreemfs.test.TestHelper;
public class ControllerIntegrationTest {
@Rule
public final TestRule testLog = TestHelper.testLog;
private static DIRRequestDispatcher dir;
private static TestEnvironment testEnv;
private static DIRConfig dirConfig;
private static RPC.UserCredentials userCredentials;
private static RPC.Auth auth = RPCAuthentication.authNone;
private static DIRClient dirClient;
private static final int NUMBER_OF_OSDS = 3;
private static OSDConfig osdConfigs[];
private static OSD osds[];
private static MRCRequestDispatcher mrc2;
private static String dirAddress;
private ConfigBuilder configBuilder;
private Controller controller;
private Client client;
@BeforeClass
public static void initializeTest() throws Exception {
FSUtils.delTree(new java.io.File(SetupUtils.TEST_DIR));
Logging.start(Logging.LEVEL_WARN, Logging.Category.tool);
dirConfig = SetupUtils.createDIRConfig();
osdConfigs = SetupUtils.createMultipleOSDConfigs(NUMBER_OF_OSDS);
dir = new DIRRequestDispatcher(dirConfig, SetupUtils.createDIRdbsConfig());
dir.startup();
dir.waitForStartup();
testEnv = new TestEnvironment(TestEnvironment.Services.DIR_CLIENT, TestEnvironment.Services.TIME_SYNC,
TestEnvironment.Services.RPC_CLIENT, TestEnvironment.Services.MRC);
testEnv.start();
userCredentials = RPC.UserCredentials.newBuilder().setUsername("test").addGroups("test").build();
dirClient = new DIRClient(new DIRServiceClient(testEnv.getRpcClient(), null),
new InetSocketAddress[] { testEnv.getDIRAddress() }, 3, 1000);
osds = new OSD[NUMBER_OF_OSDS];
for (int i = 0; i < osds.length; i++) {
osds[i] = new OSD(osdConfigs[i]);
}
dirAddress = testEnv.getDIRAddress().getHostName() + ":" + testEnv.getDIRAddress().getPort();
}
@Before
public void setUp() throws Exception {
configBuilder = BenchmarkConfig.newBuilder();
configBuilder.setDirAddress(dirAddress);
configBuilder.setUserName("test").setGroup("test");
Options options = new Options();
client = ClientFactory.createClient(dirAddress, userCredentials, null, options);
client.start();
/* check that all volumes have been deleted properly by previous tests (prevent error masking) */
assertNoVolumes("BenchVolA", "BenchVolB", "BenchVolC");
}
@After
public void tearDown() throws Exception {
client.shutdown();
}
@AfterClass
public static void shutdownTest() throws Exception {
for (int i = 0; i < osds.length; i++) {
if (osds[i] != null) {
osds[i].shutdown();
}
}
if (mrc2 != null) {
mrc2.shutdown();
mrc2 = null;
}
testEnv.shutdown();
dir.shutdown();
dir.waitForShutdown();
}
@Test
public void testSetupVolumes() throws Exception {
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB", "BenchVolC");
List volumes = Arrays.asList(client.listVolumeNames());
assertTrue(volumes.contains("BenchVolA"));
assertTrue(volumes.contains("BenchVolB"));
assertTrue(volumes.contains("BenchVolC"));
controller.teardown();
volumes = Arrays.asList(client.listVolumeNames());
assertEquals(0, volumes.size());
}
@Test
public void testSequentialBenchmark() throws Exception {
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_WRITE", 2, 10L * MiB_IN_BYTES, 2, results);
results = controller.startSequentialReadBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_READ", 2, 10L * MiB_IN_BYTES, 2, results);
controller.teardown();
}
@Test
public void testSequentialBenchmarkSeparatedRuns() throws Exception {
configBuilder.setNoCleanup();
BenchmarkConfig config = configBuilder.build();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_WRITE", 2, 10L * MiB_IN_BYTES, 2, results);
controller.teardown();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
results = controller.startSequentialReadBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_READ", 2, 10L * MiB_IN_BYTES, 2, results);
controller.teardown();
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testRandomBenchmark() throws Exception {
configBuilder.setBasefileSizeInBytes(20L * MiB_IN_BYTES);
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startRandomWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
results = controller.startRandomReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
}
@Test
public void testRandomBenchmarkSeparateRuns() throws Exception {
configBuilder.setBasefileSizeInBytes(20L * MiB_IN_BYTES).setNoCleanup();
BenchmarkConfig config = configBuilder.build();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startRandomWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
results = controller.startRandomReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testFilebasedBenchmark() throws Exception {
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startFilebasedWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
results = controller.startFilebasedReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
}
@Test
public void testFilebasedBenchmarkSeparateRuns() throws Exception {
configBuilder.setNoCleanup();
BenchmarkConfig config = configBuilder.build();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startFilebasedWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
results = controller.startFilebasedReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testConfigUser() throws Exception {
configBuilder.setUserName("test");
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("test", volume.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getUserId());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigGroup() throws Exception {
configBuilder.setGroup("test");
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("test", volume.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getGroupId());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigSeqSize() throws Exception {
long seqSize = 2L * MiB_IN_BYTES;
Volume volume = performBenchmark(seqSize, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals(seqSize, volume.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigBasefileSize() throws Exception {
long randSize = 1L * MiB_IN_BYTES;
long basefileSize = 20L * MiB_IN_BYTES;
configBuilder.setBasefileSizeInBytes(basefileSize);
Volume volume = performBenchmark(randSize, configBuilder, BenchmarkType.RAND_WRITE);
assertEquals(basefileSize, volume.getAttr(userCredentials, "benchmarks/basefile").getSize());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigFilesSize() throws Exception {
int fileSize = 8 * KiB_IN_BYTES;
configBuilder.setFilesize(fileSize);
Volume volume = performBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.FILES_WRITE);
int numberOfFiles = (MiB_IN_BYTES) / (8 * KiB_IN_BYTES);
for (int i = 0; i < numberOfFiles; i++) {
long fileSizeActual = volume.getAttr(userCredentials, "benchmarks/randomBenchmark/benchFile" + i).getSize();
assertEquals(fileSize, fileSizeActual);
}
deleteVolumes("BenchVolA");
}
@Test
public void testConfigStripeSize() throws Exception {
int stripeSize = 64 * KiB_IN_BYTES;
configBuilder.setStripeSizeInBytes(stripeSize);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("size:64", sp_values.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
@Test
public void testConfigStripeWidth() throws Exception {
configBuilder.setStripeWidth(2);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("width:2", sp_values.split(",")[1].replace("\"", ""));
deleteVolumes("BenchVolA");
}
/*
* Test, that using an existing volume doesn't change the stripe size and width previously set on said volume.
*/
@Test
public void testConfigStripeSizeWidthNotSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test", GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 1024, 2, volumeAttributes);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("width:2", sp_values.split(",")[1].replace("\"", ""));
assertEquals("size:1024", sp_values.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
/*
* Test, that setting stripe size and width overrides values of an existing volume.
*/
@Test
public void testConfigStripeSizeWidthSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test", GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 128, 1, volumeAttributes);
configBuilder.setStripeSizeInBytes(256*1024).setStripeWidth(2);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("width:2", sp_values.split(",")[1].replace("\"", ""));
assertEquals("size:256", sp_values.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
@Test
public void testConfigOSDSelectionPolicy() throws Exception {
configBuilder.setOsdSelectionPolicies("1001,3003");
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("1001,3003", volumeA.getOSDSelectionPolicy(userCredentials));
deleteVolumes("BenchVolA");
}
/*
* Test, that using an existing volume doesn't change the osd selection policies previously set on said volume.
*/
@Test
public void testConfigOSDSelectionPolicyNotSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test", GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 128, 1, volumeAttributes);
Volume volume = client.openVolume("BenchVolA", null, new Options());
volume.setOSDSelectionPolicy(userCredentials, "1001,3003");
volume.close();
configBuilder.setUserName("test").setGroup("test");
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("1001,3003", volumeA.getOSDSelectionPolicy(userCredentials));
deleteVolumes("BenchVolA");
}
@Test
public void testConfigOSDSelectionUUID() throws Exception {
/* perform benchmark on osd "UUID:localhost:42640" */
configBuilder.setSelectOsdsByUuid("UUID:localhost:42640");
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
/* perform benchmark on osd "UUID:localhost:42641" */
configBuilder = BenchmarkConfig.newBuilder();
configBuilder.setUserName("test").setGroup("test");
configBuilder.setDirAddress(dirAddress);
configBuilder.setSelectOsdsByUuid("UUID:localhost:42641").setNoCleanup();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolB");
controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 1);
controller.teardown();
Volume volumeB = client.openVolume("BenchVolB", null, new Options());
/* assert, that the benchmark files were created on the correct osd */
assertEquals("1002", volumeA.getOSDSelectionPolicy(userCredentials));
assertEquals("UUID:localhost:42640",
volumeA.getSuitableOSDs(userCredentials, "benchmarks/sequentialBenchmark/benchFile0", 1).get(0));
assertEquals("1002", volumeB.getOSDSelectionPolicy(userCredentials));
assertEquals("UUID:localhost:42641",
volumeB.getSuitableOSDs(userCredentials, "benchmarks/sequentialBenchmark/benchFile0", 1).get(0));
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testConfigReplicationPolicy() throws Exception {
configBuilder.setReplicationPolicy("WqRq");
configBuilder.setReplicationFactor(3);
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String default_rp = volumeA.getXAttr(userCredentials,"", "xtreemfs.default_rp");
assertEquals("replication-factor:3", default_rp.split(",")[0].replace("\"", "").replace("{", ""));
assertEquals("update-policy:WqRq", default_rp.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
/*
* Tests, that performing a benchmark on a volume for which a default replication policy was set does not override the policy
*/
@Test
public void testConfigReplicationPolicyNotSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test",
GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 128, 1, volumeAttributes);
Volume volume = client.openVolume("BenchVolA", null, new Options());
volume.setDefaultReplicationPolicy(userCredentials, "/", "WqRq", 3, 0);
volume.close();
configBuilder.setUserName("test").setGroup("test");
Volume volumeA = performBenchmark(10L * BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String default_rp = volumeA.getXAttr(userCredentials, "", "xtreemfs.default_rp");
assertEquals("replication-factor:3", default_rp.split(",")[0].replace("\"", "").replace("{", ""));
assertEquals("update-policy:WqRq", default_rp.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
/* The NoCleanup option is testet implicitly in all the above Config tests */
@Test
public void testConfigNoCleanupVolumes() throws Exception {
configBuilder.setNoCleanupVolumes();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB", "BenchVolC");
controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 3);
Volume volumeA = client.openVolume("BenchVolA", null, new Options());
Volume volumeB = client.openVolume("BenchVolB", null, new Options());
Volume volumeC = client.openVolume("BenchVolC", null, new Options());
/* the benchFiles are still there after the benchmark */
long seqSize = 10L * BenchmarkUtils.MiB_IN_BYTES;
assertEquals(seqSize, volumeA.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
assertEquals(seqSize, volumeB.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
assertEquals(seqSize, volumeC.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
controller.teardown();
/*
* after the teardown (which includes the deletion of the benchmark volumes and files), only the volumes are
* present
*/
assertEquals(0, (int) Integer.valueOf(volumeA.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(0, (int) Integer.valueOf(volumeB.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(0, (int) Integer.valueOf(volumeC.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(0, (int) Integer.valueOf(volumeA.getXAttr(userCredentials, "", "xtreemfs.used_space")));
assertEquals(0, (int) Integer.valueOf(volumeB.getXAttr(userCredentials, "", "xtreemfs.used_space")));
assertEquals(0, (int) Integer.valueOf(volumeC.getXAttr(userCredentials, "", "xtreemfs.used_space")));
deleteVolumes("BenchVolA", "BenchVolB", "BenchVolC");
}
@Test
public void testConfigNoCleanupBasefile() throws Exception {
long basefileSize = 30L * BenchmarkUtils.MiB_IN_BYTES;
long randSize = BenchmarkUtils.MiB_IN_BYTES;
configBuilder.setNoCleanupBasefile().setBasefileSizeInBytes(basefileSize)
.setNoCleanupVolumes();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA");
controller.startRandomWriteBenchmark(randSize, 1);
/* the filebased benchmark is used to show, that really files are (created and) deleted, except the basefile */
controller.startFilebasedWriteBenchmark(randSize, 1);
Volume volume = client.openVolume("BenchVolA", null, new Options());
/* number of files from filebased benchmark + basefile */
int numberOfFiles = (int) (randSize / (4 * BenchmarkUtils.KiB_IN_BYTES)) + 1;
assertEquals(numberOfFiles, (int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(basefileSize + randSize,
(int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.used_space")));
controller.teardown();
/*
* after the teardown (which includes the deletion of the benchmark volumes and files), only the basefile is
* still present
*/
assertEquals(basefileSize, volume.getAttr(userCredentials, "benchmarks/basefile").getSize());
assertEquals(1, (int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(basefileSize, (int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.used_space")));
}
private void assertNoVolumes(String... volumes) throws Exception {
for (String volumeName : volumes) {
try {
Volume volume = client.openVolume(volumeName, null, new Options());
fail("VolumeNotFoundException expected");
} catch (VolumeNotFoundException e) {
// ok (Exception expected)
}
}
}
private void compareResults(String type, int threads, long size, int numberOfResults, List<BenchmarkResult> results) {
int resultCounter = 0;
for (BenchmarkResult result : results) {
resultCounter++;
String benchmarkType = result.getBenchmarkType().toString();
assertEquals(type, benchmarkType);
assertEquals(threads, result.getNumberOfReadersOrWriters());
assertEquals(size, result.getRequestedSize());
assertEquals(size, result.getActualSize());
}
assertEquals(numberOfResults, resultCounter);
}
private Volume performBenchmark(long size, ConfigBuilder configBuilder, BenchmarkType type) throws Exception {
configBuilder.setNoCleanup();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA");
switch (type) {
case SEQ_WRITE:
controller.startSequentialWriteBenchmark(size, 1);
break;
case RAND_WRITE:
controller.startRandomWriteBenchmark(size, 1);
break;
case FILES_WRITE:
controller.startFilebasedWriteBenchmark(size, 1);
break;
}
controller.teardown();
Volume volume = client.openVolume("BenchVolA", null, new Options());
return volume;
}
private void deleteVolumes(String... volumeNames) throws IOException {
for (String volumeName : volumeNames) {
client.deleteVolume(auth, userCredentials, volumeName);
}
}
}
|
java/servers/test/org/xtreemfs/test/common/benchmark/ControllerIntegrationTest.java
|
package org.xtreemfs.test.common.benchmark;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.xtreemfs.common.benchmark.BenchmarkUtils.KiB_IN_BYTES;
import static org.xtreemfs.common.benchmark.BenchmarkUtils.MiB_IN_BYTES;
import static org.xtreemfs.foundation.pbrpc.client.RPCAuthentication.authNone;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.xtreemfs.common.benchmark.BenchmarkConfig;
import org.xtreemfs.common.benchmark.BenchmarkConfig.ConfigBuilder;
import org.xtreemfs.common.benchmark.BenchmarkResult;
import org.xtreemfs.common.benchmark.BenchmarkUtils;
import org.xtreemfs.common.benchmark.BenchmarkUtils.BenchmarkType;
import org.xtreemfs.common.benchmark.Controller;
import org.xtreemfs.common.libxtreemfs.Client;
import org.xtreemfs.common.libxtreemfs.ClientFactory;
import org.xtreemfs.common.libxtreemfs.Options;
import org.xtreemfs.common.libxtreemfs.Volume;
import org.xtreemfs.common.libxtreemfs.exceptions.VolumeNotFoundException;
import org.xtreemfs.dir.DIRClient;
import org.xtreemfs.dir.DIRConfig;
import org.xtreemfs.dir.DIRRequestDispatcher;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC;
import org.xtreemfs.foundation.util.FSUtils;
import org.xtreemfs.mrc.MRCRequestDispatcher;
import org.xtreemfs.osd.OSD;
import org.xtreemfs.osd.OSDConfig;
import org.xtreemfs.pbrpc.generatedinterfaces.DIRServiceClient;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes;
import org.xtreemfs.test.SetupUtils;
import org.xtreemfs.test.TestEnvironment;
import org.xtreemfs.test.TestHelper;
public class ControllerIntegrationTest {
@Rule
public final TestRule testLog = TestHelper.testLog;
private static DIRRequestDispatcher dir;
private static TestEnvironment testEnv;
private static DIRConfig dirConfig;
private static RPC.UserCredentials userCredentials;
private static RPC.Auth auth = RPCAuthentication.authNone;
private static DIRClient dirClient;
private static final int NUMBER_OF_OSDS = 3;
private static OSDConfig osdConfigs[];
private static OSD osds[];
private static MRCRequestDispatcher mrc2;
private static String dirAddress;
private ConfigBuilder configBuilder;
private Controller controller;
private Client client;
@BeforeClass
public static void initializeTest() throws Exception {
FSUtils.delTree(new java.io.File(SetupUtils.TEST_DIR));
Logging.start(Logging.LEVEL_WARN, Logging.Category.tool);
dirConfig = SetupUtils.createDIRConfig();
osdConfigs = SetupUtils.createMultipleOSDConfigs(NUMBER_OF_OSDS);
dir = new DIRRequestDispatcher(dirConfig, SetupUtils.createDIRdbsConfig());
dir.startup();
dir.waitForStartup();
testEnv = new TestEnvironment(TestEnvironment.Services.DIR_CLIENT, TestEnvironment.Services.TIME_SYNC,
TestEnvironment.Services.RPC_CLIENT, TestEnvironment.Services.MRC);
testEnv.start();
userCredentials = RPC.UserCredentials.newBuilder().setUsername("test").addGroups("test").build();
dirClient = new DIRClient(new DIRServiceClient(testEnv.getRpcClient(), null),
new InetSocketAddress[] { testEnv.getDIRAddress() }, 3, 1000);
osds = new OSD[NUMBER_OF_OSDS];
for (int i = 0; i < osds.length; i++) {
osds[i] = new OSD(osdConfigs[i]);
}
dirAddress = testEnv.getDIRAddress().getHostName() + ":" + testEnv.getDIRAddress().getPort();
}
@Before
public void setUp() throws Exception {
configBuilder = BenchmarkConfig.newBuilder();
configBuilder.setDirAddress(dirAddress);
configBuilder.setUserName("test").setGroup("test");
Options options = new Options();
client = ClientFactory.createClient(dirAddress, userCredentials, null, options);
client.start();
/* check that all volumes have been deleted properly by previous tests (prevent error masking) */
assertNoVolumes("BenchVolA", "BenchVolB", "BenchVolC");
}
@After
public void tearDown() throws Exception {
client.shutdown();
}
@AfterClass
public static void shutdownTest() throws Exception {
for (int i = 0; i < osds.length; i++) {
if (osds[i] != null) {
osds[i].shutdown();
}
}
if (mrc2 != null) {
mrc2.shutdown();
mrc2 = null;
}
testEnv.shutdown();
dir.shutdown();
dir.waitForShutdown();
}
@Test
public void testSetupVolumes() throws Exception {
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB", "BenchVolC");
List volumes = Arrays.asList(client.listVolumeNames());
assertTrue(volumes.contains("BenchVolA"));
assertTrue(volumes.contains("BenchVolB"));
assertTrue(volumes.contains("BenchVolC"));
controller.teardown();
volumes = Arrays.asList(client.listVolumeNames());
assertEquals(0, volumes.size());
}
@Test
public void testSequentialBenchmark() throws Exception {
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_WRITE", 2, 10L * MiB_IN_BYTES, 2, results);
results = controller.startSequentialReadBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_READ", 2, 10L * MiB_IN_BYTES, 2, results);
controller.teardown();
}
@Test
public void testSequentialBenchmarkSeparatedRuns() throws Exception {
configBuilder.setNoCleanup();
BenchmarkConfig config = configBuilder.build();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_WRITE", 2, 10L * MiB_IN_BYTES, 2, results);
controller.teardown();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
results = controller.startSequentialReadBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("SEQ_READ", 2, 10L * MiB_IN_BYTES, 2, results);
controller.teardown();
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testRandomBenchmark() throws Exception {
configBuilder.setBasefileSizeInBytes(20L * MiB_IN_BYTES);
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startRandomWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
results = controller.startRandomReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
}
@Test
public void testRandomBenchmarkSeparateRuns() throws Exception {
configBuilder.setBasefileSizeInBytes(20L * MiB_IN_BYTES).setNoCleanup();
BenchmarkConfig config = configBuilder.build();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startRandomWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
results = controller.startRandomReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("RAND_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testFilebasedBenchmark() throws Exception {
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startFilebasedWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
results = controller.startFilebasedReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
}
@Test
public void testFilebasedBenchmarkSeparateRuns() throws Exception {
configBuilder.setNoCleanup();
BenchmarkConfig config = configBuilder.build();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
List<BenchmarkResult> results = controller.startFilebasedWriteBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_WRITE", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
controller = new Controller(config);
controller.setupVolumes("BenchVolA", "BenchVolB");
results = controller.startFilebasedReadBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, 2);
compareResults("FILES_READ", 2, 1L * MiB_IN_BYTES, 2, results);
controller.teardown();
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testConfigUser() throws Exception {
configBuilder.setUserName("test");
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("test", volume.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getUserId());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigGroup() throws Exception {
configBuilder.setGroup("test");
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("test", volume.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getGroupId());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigSeqSize() throws Exception {
long seqSize = 2L * MiB_IN_BYTES;
Volume volume = performBenchmark(seqSize, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals(seqSize, volume.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigBasefileSize() throws Exception {
long randSize = 1L * MiB_IN_BYTES;
long basefileSize = 20L * MiB_IN_BYTES;
configBuilder.setBasefileSizeInBytes(basefileSize);
Volume volume = performBenchmark(randSize, configBuilder, BenchmarkType.RAND_WRITE);
assertEquals(basefileSize, volume.getAttr(userCredentials, "benchmarks/basefile").getSize());
deleteVolumes("BenchVolA");
}
@Test
public void testConfigFilesSize() throws Exception {
int fileSize = 8 * KiB_IN_BYTES;
configBuilder.setFilesize(fileSize);
Volume volume = performBenchmark(1L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.FILES_WRITE);
int numberOfFiles = (MiB_IN_BYTES) / (8 * KiB_IN_BYTES);
for (int i = 0; i < numberOfFiles; i++) {
long fileSizeActual = volume.getAttr(userCredentials, "benchmarks/randomBenchmark/benchFile" + i).getSize();
assertEquals(fileSize, fileSizeActual);
}
deleteVolumes("BenchVolA");
}
@Test
public void testConfigStripeSize() throws Exception {
int stripeSize = 64 * KiB_IN_BYTES;
configBuilder.setStripeSizeInBytes(stripeSize);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("size:64", sp_values.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
@Test
public void testConfigStripeWidth() throws Exception {
configBuilder.setStripeWidth(2);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("width:2", sp_values.split(",")[1].replace("\"", ""));
deleteVolumes("BenchVolA");
}
/*
* Test, that using an existing volume doesn't change the stripe size and width previously set on said volume.
*/
@Test
public void testConfigStripeSizeWidthNotSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test", GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 1024, 2, volumeAttributes);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("width:2", sp_values.split(",")[1].replace("\"", ""));
assertEquals("size:1024", sp_values.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
/*
* Test, that setting stripe size and width overrides values of an existing volume.
*/
@Test
public void testConfigStripeSizeWidthSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test", GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 128, 1, volumeAttributes);
configBuilder.setStripeSizeInBytes(256*1024).setStripeWidth(2);
Volume volume = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String sp_values = volume.getXAttr(userCredentials, "", "xtreemfs.default_sp");
assertEquals("width:2", sp_values.split(",")[1].replace("\"", ""));
assertEquals("size:256", sp_values.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
@Test
public void testConfigOSDSelectionPolicy() throws Exception {
configBuilder.setOsdSelectionPolicies("1001,3003");
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("1001,3003", volumeA.getOSDSelectionPolicy(userCredentials));
deleteVolumes("BenchVolA");
}
/*
* Test, that using an existing volume doesn't change the osd selection policies previously set on said volume.
*/
@Test
public void testConfigOSDSelectionPolicyNotSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test", GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 128, 1, volumeAttributes);
Volume volume = client.openVolume("BenchVolA", null, new Options());
volume.setOSDSelectionPolicy(userCredentials, "1001,3003");
volume.close();
configBuilder.setUserName("test").setGroup("test");
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
assertEquals("1001,3003", volumeA.getOSDSelectionPolicy(userCredentials));
deleteVolumes("BenchVolA");
}
@Test
public void testConfigOSDSelectionUUID() throws Exception {
/* perform benchmark on osd "UUID:localhost:42640" */
configBuilder.setSelectOsdsByUuid("UUID:localhost:42640");
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
/* perform benchmark on osd "UUID:localhost:42641" */
configBuilder = BenchmarkConfig.newBuilder();
configBuilder.setUserName("test").setGroup("test");
configBuilder.setDirAddress(dirAddress);
configBuilder.setSelectOsdsByUuid("UUID:localhost:42641").setNoCleanup();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolB");
controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 1);
controller.teardown();
Volume volumeB = client.openVolume("BenchVolB", null, new Options());
/* assert, that the benchmark files were created on the correct osd */
assertEquals("1002", volumeA.getOSDSelectionPolicy(userCredentials));
assertEquals("UUID:localhost:42640",
volumeA.getSuitableOSDs(userCredentials, "benchmarks/sequentialBenchmark/benchFile0", 1).get(0));
assertEquals("1002", volumeB.getOSDSelectionPolicy(userCredentials));
assertEquals("UUID:localhost:42641",
volumeB.getSuitableOSDs(userCredentials, "benchmarks/sequentialBenchmark/benchFile0", 1).get(0));
deleteVolumes("BenchVolA", "BenchVolB");
}
@Test
public void testConfigReplicationPolicy() throws Exception {
configBuilder.setReplicationPolicy("WqRq");
configBuilder.setReplicationFactor(3);
Volume volumeA = performBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String default_rp = volumeA.getXAttr(userCredentials,"", "xtreemfs.default_rp");
assertEquals("replication-factor:3", default_rp.split(",")[0].replace("\"", "").replace("{", ""));
assertEquals("update-policy:WqRq", default_rp.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
/*
* Tests, that performing a benchmark on a volume for which a default replication policy was set does not override the policy
*/
@Test
public void testConfigReplicationPolicyNotSet() throws Exception {
List<GlobalTypes.KeyValuePair> volumeAttributes = new ArrayList<GlobalTypes.KeyValuePair>();
client.createVolume(authNone, userCredentials, "BenchVolA", 511, "test", "test",
GlobalTypes.AccessControlPolicyType.ACCESS_CONTROL_POLICY_POSIX,
GlobalTypes.StripingPolicyType.STRIPING_POLICY_RAID0, 128, 1, volumeAttributes);
Volume volume = client.openVolume("BenchVolA", null, new Options());
volume.setDefaultReplicationPolicy(userCredentials, "/", "WqRq", 3, 0);
volume.close();
configBuilder.setUserName("test").setGroup("test");
Volume volumeA = performBenchmark(10L * BenchmarkUtils.MiB_IN_BYTES, configBuilder, BenchmarkType.SEQ_WRITE);
String default_rp = volumeA.getXAttr(userCredentials, "", "xtreemfs.default_rp");
assertEquals("replication-factor:3", default_rp.split(",")[0].replace("\"", "").replace("{", ""));
assertEquals("update-policy:WqRq", default_rp.split(",")[2].replace("\"", "").replace("}", ""));
deleteVolumes("BenchVolA");
}
/* The NoCleanup option is testet implicitly in all the above Config tests */
@Test
public void testConfigNoCleanupVolumes() throws Exception {
configBuilder.setNoCleanupVolumes();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA", "BenchVolB", "BenchVolC");
controller.startSequentialWriteBenchmark(10L*BenchmarkUtils.MiB_IN_BYTES, 3);
Volume volumeA = client.openVolume("BenchVolA", null, new Options());
Volume volumeB = client.openVolume("BenchVolB", null, new Options());
Volume volumeC = client.openVolume("BenchVolC", null, new Options());
/* the benchFiles are still there after the benchmark */
long seqSize = 10L * BenchmarkUtils.MiB_IN_BYTES;
assertEquals(seqSize, volumeA.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
assertEquals(seqSize, volumeB.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
assertEquals(seqSize, volumeC.getAttr(userCredentials, "benchmarks/sequentialBenchmark/benchFile0").getSize());
controller.teardown();
/*
* after the teardown (which includes the deletion of the benchmark volumes and files), only the volumes are
* present
*/
assertEquals(0, (int) Integer.valueOf(volumeA.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(0, (int) Integer.valueOf(volumeB.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(0, (int) Integer.valueOf(volumeC.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(0, (int) Integer.valueOf(volumeA.getXAttr(userCredentials, "", "xtreemfs.used_space")));
assertEquals(0, (int) Integer.valueOf(volumeB.getXAttr(userCredentials, "", "xtreemfs.used_space")));
assertEquals(0, (int) Integer.valueOf(volumeC.getXAttr(userCredentials, "", "xtreemfs.used_space")));
deleteVolumes("BenchVolA", "BenchVolB", "BenchVolC");
}
@Test
public void testConfigNoCleanupBasefile() throws Exception {
long basefileSize = 30L * BenchmarkUtils.MiB_IN_BYTES;
long randSize = BenchmarkUtils.MiB_IN_BYTES;
configBuilder.setNoCleanupBasefile().setBasefileSizeInBytes(basefileSize)
.setNoCleanupVolumes();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA");
controller.startRandomWriteBenchmark(randSize, 1);
/* the filebased benchmark is used to show, that really files are (created and) deleted, except the basefile */
controller.startFilebasedWriteBenchmark(randSize, 1);
Volume volume = client.openVolume("BenchVolA", null, new Options());
/* number of files from filebased benchmark + basefile */
int numberOfFiles = (int) (randSize / (4 * BenchmarkUtils.KiB_IN_BYTES)) + 1;
assertEquals(numberOfFiles, (int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(basefileSize + randSize,
(int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.used_space")));
controller.teardown();
/*
* after the teardown (which includes the deletion of the benchmark volumes and files), only the basefile is
* still present
*/
assertEquals(basefileSize, volume.getAttr(userCredentials, "benchmarks/basefile").getSize());
assertEquals(1, (int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.num_files")));
assertEquals(basefileSize, (int) Integer.valueOf(volume.getXAttr(userCredentials, "", "xtreemfs.used_space")));
}
private void assertNoVolumes(String... volumes) throws Exception {
for (String volumeName : volumes) {
try {
Volume volume = client.openVolume(volumeName, null, new Options());
fail("VolumeNotFoundException expected");
} catch (VolumeNotFoundException e) {
// ok (Exception expected)
}
}
}
private void compareResults(String type, int threads, long size, int numberOfResults, List<BenchmarkResult> results) {
int resultCounter = 0;
for (BenchmarkResult result : results) {
resultCounter++;
String benchmarkType = result.getBenchmarkType().toString();
assertEquals(type, benchmarkType);
assertEquals(threads, result.getNumberOfReadersOrWriters());
assertEquals(size, result.getRequestedSize());
assertEquals(size, result.getActualSize());
}
assertEquals(numberOfResults, resultCounter);
}
private Volume performBenchmark(long size, ConfigBuilder configBuilder, BenchmarkType type) throws Exception {
configBuilder.setNoCleanup();
controller = new Controller(configBuilder.build());
controller.setupVolumes("BenchVolA");
switch (type) {
case SEQ_WRITE:
controller.startSequentialWriteBenchmark(size, 1);
break;
case RAND_WRITE:
controller.startRandomWriteBenchmark(size, 1);
break;
case FILES_WRITE:
controller.startFilebasedWriteBenchmark(size, 1);
break;
}
controller.teardown();
Volume volume = client.openVolume("BenchVolA", null, new Options());
return volume;
}
private void deleteVolumes(String... volumeNames) throws IOException {
for (String volumeName : volumeNames) {
client.deleteVolume(auth, userCredentials, volumeName);
}
}
private void printResults(List<BenchmarkResult> results) {
System.err.println("Type\t\t\tThreads\t\tTime\tSpeed\tRequested\t\tCount");
for (BenchmarkResult res : results) {
System.err.println(res.getBenchmarkType() + "\t\t" + res.getNumberOfReadersOrWriters() + "\t\t\t"
+ res.getTimeInSec() + "\t" + res.getSpeedInMiBPerSec() + "\t" + res.getRequestedSize()
+ "\t\t" + res.getActualSize());
}
}
}
|
servers: removed unused method
|
java/servers/test/org/xtreemfs/test/common/benchmark/ControllerIntegrationTest.java
|
servers: removed unused method
|
<ide><path>ava/servers/test/org/xtreemfs/test/common/benchmark/ControllerIntegrationTest.java
<ide> client.deleteVolume(auth, userCredentials, volumeName);
<ide> }
<ide> }
<del>
<del> private void printResults(List<BenchmarkResult> results) {
<del> System.err.println("Type\t\t\tThreads\t\tTime\tSpeed\tRequested\t\tCount");
<del> for (BenchmarkResult res : results) {
<del> System.err.println(res.getBenchmarkType() + "\t\t" + res.getNumberOfReadersOrWriters() + "\t\t\t"
<del> + res.getTimeInSec() + "\t" + res.getSpeedInMiBPerSec() + "\t" + res.getRequestedSize()
<del> + "\t\t" + res.getActualSize());
<del> }
<del> }
<del>
<ide> }
|
|
Java
|
apache-2.0
|
373c14d5c8ae9a84f21761e3a4c4668189fc91fa
| 0 |
phimpme/android-prototype,phimpme/android-prototype,phimpme/android-prototype,phimpme/android-prototype
|
package org.fossasia.phimpme.leafpic.activities;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.view.IconicsImageView;
import org.fossasia.phimpme.R;
import org.fossasia.phimpme.base.SharedMediaActivity;
import org.fossasia.phimpme.leafpic.SelectAlbumBottomSheet;
import org.fossasia.phimpme.leafpic.adapters.AlbumsAdapter;
import org.fossasia.phimpme.leafpic.adapters.MediaAdapter;
import org.fossasia.phimpme.leafpic.data.Album;
import org.fossasia.phimpme.leafpic.data.CustomAlbumsHelper;
import org.fossasia.phimpme.leafpic.data.HandlingAlbums;
import org.fossasia.phimpme.leafpic.data.Media;
import org.fossasia.phimpme.leafpic.data.base.FilterMode;
import org.fossasia.phimpme.leafpic.data.base.SortingOrder;
import org.fossasia.phimpme.leafpic.data.providers.StorageProvider;
import org.fossasia.phimpme.leafpic.util.Affix;
import org.fossasia.phimpme.leafpic.util.AlertDialogsHelper;
import org.fossasia.phimpme.leafpic.util.ContentHelper;
import org.fossasia.phimpme.leafpic.util.Measure;
import org.fossasia.phimpme.leafpic.util.PreferenceUtil;
import org.fossasia.phimpme.leafpic.util.SecurityHelper;
import org.fossasia.phimpme.leafpic.util.StringUtils;
import org.fossasia.phimpme.leafpic.views.GridSpacingItemDecoration;
import org.fossasia.phimpme.utilities.ActivitySwitchHelper;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.DATE;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.NAME;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.NUMERIC;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.SIZE;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.TYPE;
public class LFMainActivity extends SharedMediaActivity {
private static String TAG = "AlbumsAct";
private int REQUEST_CODE_SD_CARD_PERMISSIONS = 42;
private CustomAlbumsHelper customAlbumsHelper = CustomAlbumsHelper.getInstance(LFMainActivity.this);
private PreferenceUtil SP;
private SecurityHelper securityObj;
private RecyclerView rvAlbums;
private AlbumsAdapter albumsAdapter;
private GridSpacingItemDecoration rvAlbumsDecoration;
private RecyclerView rvMedia;
private MediaAdapter mediaAdapter;
private GridSpacingItemDecoration rvMediaDecoration;
private DrawerLayout mDrawerLayout;
private Toolbar toolbar;
private SelectAlbumBottomSheet bottomSheetDialogFragment;
private SwipeRefreshLayout swipeRefreshLayout;
private boolean hidden = false, pickMode = false, editMode = false, albumsMode = true, firstLaunch = true;
//To handle all photos/Album conditions
public boolean all_photos = false;
final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
public static ArrayList<Media> listAll;
public int size;
public int pos;
private ArrayList<Media> media;
private ArrayList<Media> selectedMedias = new ArrayList<>();
/*
editMode- When true, user can select items by clicking on them one by one
*/
/**
* Handles long clicks on photos.
* If first long click on photo (editMode = false), go into selection mode and set editMode = true.
* If not first long click, means that already in selection mode- s0 select all photos upto chosen one.
*/
private View.OnLongClickListener photosOnLongClickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Media m = (Media) v.findViewById(R.id.photo_path).getTag();
//If first long press, turn on selection mode
if (!all_photos) {
if (!editMode) {
mediaAdapter.notifyItemChanged(getAlbum().toggleSelectPhoto(m));
editMode = true;
} else
getAlbum().selectAllPhotosUpTo(getAlbum().getIndex(m), mediaAdapter);
invalidateOptionsMenu();
} else
if(!editMode){
mediaAdapter.notifyItemChanged(toggleSelectPhoto(getImagePosition(m.getPath())));
editMode = true;
mediaAdapter.swapDataSet(listAll);
}
else selectAllPhotosUpTo(getImagePosition(m.getPath()),mediaAdapter);
return true;
}
};
private int toggleSelectPhoto(int index) {
if (media.get(index) != null) {
media.get(index).setSelected(!media.get(index).isSelected());
if (media.get(index).isSelected())
selectedMedias.add(media.get(index));
else
selectedMedias.remove(media.get(index));
}
if(selectedMedias.size()==0){
editMode = false;
toolbar.setTitle(getString(R.string.all));
}
else
toolbar.setTitle(selectedMedias.size() + "/" + size);
invalidateOptionsMenu();
return index;
}
public void clearSelectedPhotos() {
for (Media m : media)
m.setSelected(false);
if (selectedMedias!=null)
selectedMedias.clear();
toolbar.setTitle(getString(R.string.all));
}
public void selectAllPhotos(){
for (Media m : media) {
m.setSelected(true);
selectedMedias.add(m);
}
toolbar.setTitle(selectedMedias.size() + "/" + size);
}
public void selectAllPhotosUpTo(int targetIndex, MediaAdapter adapter) {
int indexRightBeforeOrAfter = -1;
int indexNow;
for (Media sm : selectedMedias) {
indexNow = media.indexOf(sm);
if (indexRightBeforeOrAfter == -1) indexRightBeforeOrAfter = indexNow;
if (indexNow > targetIndex) break;
indexRightBeforeOrAfter = indexNow;
}
if (indexRightBeforeOrAfter != -1) {
for (int index = Math.min(targetIndex, indexRightBeforeOrAfter); index <= Math.max(targetIndex, indexRightBeforeOrAfter); index++) {
if (media.get(index) != null && !media.get(index).isSelected()) {
media.get(index).setSelected(true);
selectedMedias.add(media.get(index));
adapter.notifyItemChanged(index);
}
}
}
toolbar.setTitle(selectedMedias.size() + "/" + size);
}
/**
* Handles short clicks on photos.
* If in selection mode (editMode = true) , select the photo if it is unselected and unselect it if it's selected.
* This mechanism makes it possible to select photos one by one by short-clicking on them.
* If not in selection mode (editMode = false) , get current photo from album and open it in singleActivity
*/
private View.OnClickListener photosOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Media m = (Media) v.findViewById(R.id.photo_path).getTag();
if (all_photos) {
pos = getImagePosition(m.getPath());
}
if (!all_photos) {
if (!pickMode) {
//if in selection mode, toggle the selected/unselect state of photo
if (editMode) {
mediaAdapter.notifyItemChanged(getAlbum().toggleSelectPhoto(m));
invalidateOptionsMenu();
} else {
getAlbum().setCurrentPhotoIndex(m);
Intent intent = new Intent(LFMainActivity.this, SingleMediaActivity.class);
intent.putExtra("path",Uri.fromFile(new File(m.getPath())).toString());
intent.setAction(SingleMediaActivity.ACTION_OPEN_ALBUM);
startActivity(intent);
}
} else {
setResult(RESULT_OK, new Intent().setData(m.getUri()));
finish();
}
} else {
if(!editMode) {
Intent intent = new Intent(REVIEW_ACTION, Uri.fromFile(new File(m.getPath())));
intent.putExtra(getString(R.string.all_photo_mode), true);
intent.putExtra(getString(R.string.position), pos);
intent.putExtra(getString(R.string.allMediaSize), size);
intent.setClass(getApplicationContext(), SingleMediaActivity.class);
startActivity(intent);
}
else mediaAdapter.notifyItemChanged(toggleSelectPhoto(getImagePosition(m.getPath())));
}
}
};
private View.OnLongClickListener albumOnLongCLickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(((Album) v.findViewById(R.id.album_name).getTag())));
editMode = true;
invalidateOptionsMenu();
return true;
}
};
private View.OnClickListener albumOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Album album = (Album) v.findViewById(R.id.album_name).getTag();
//int index = Integer.parseInt(v.findViewById(R.id.album_name).getTag().toString());
if (editMode) {
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(album));
invalidateOptionsMenu();
} else {
getAlbums().setCurrentAlbum(album);
displayCurrentAlbumMedia(true);
setRecentApp(getAlbums().getCurrentAlbum().getName());
}
}
};
public int getImagePosition(String path) {
int pos = 0;
for (int i = 0; i < listAll.size(); i++) {
if (listAll.get(i).getPath().equals(path)) {
pos = i;
break;
}
}
return pos;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TAG","lfmain");
SP = PreferenceUtil.getInstance(getApplicationContext());
albumsMode = true;
editMode = false;
securityObj = new SecurityHelper(LFMainActivity.this);
if (getIntent().getExtras()!=null)
pickMode = getIntent().getExtras().getBoolean(SplashScreen.PICK_MODE);
listAll = StorageProvider.getAllShownImages(LFMainActivity.this);
size = listAll.size();
media = listAll;
initUI();
displayData(getIntent().getExtras());
}
@Override
public void onResume() {
super.onResume();
ActivitySwitchHelper.setContext(this);
securityObj.updateSecuritySetting();
setupUI();
getAlbums().clearSelectedAlbums();
getAlbum().clearSelectedPhotos();
if(all_photos)
mediaAdapter.swapDataSet(listAll);
if(!all_photos) {
if (SP.getBoolean("auto_update_media", false)) {
if (albumsMode) {
if (!firstLaunch) new PrepareAlbumTask().execute();
} else new PreparePhotosTask().execute();
} else {
albumsAdapter.notifyDataSetChanged();
mediaAdapter.notifyDataSetChanged();
}
}
invalidateOptionsMenu();
firstLaunch = false;
}
private void displayCurrentAlbumMedia(boolean reload) {
toolbar.setTitle(getAlbum().getName());
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mediaAdapter.swapDataSet(getAlbum().getMedia());
if (reload) new PreparePhotosTask().execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
albumsMode = editMode = false;
invalidateOptionsMenu();
}
private void displayAllMedia(boolean reload) {
clearSelectedPhotos();
toolbar.setTitle(getString(R.string.all_media));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mediaAdapter.swapDataSet(listAll);
if (reload) new PrepareAllPhotos().execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
albumsMode = editMode = false;
invalidateOptionsMenu();
}
private void displayAlbums() {
all_photos = false;
displayAlbums(true);
}
private void displayAlbums(boolean reload) {
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_menu));
toolbar.setTitle(getString(R.string.app_name));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
if (reload) new PrepareAlbumTask().execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
albumsMode = true;
editMode = false;
invalidateOptionsMenu();
mediaAdapter.swapDataSet(new ArrayList<Media>());
rvMedia.scrollToPosition(0);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private boolean displayData(Bundle data) {
if (data != null) {
switch (data.getInt(SplashScreen.CONTENT)) {
case SplashScreen.ALBUMS_PREFETCHED:
displayAlbums(false);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(true);
return true;
case SplashScreen.ALBUMS_BACKUP:
displayAlbums(true);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(true);
return true;
case SplashScreen.PHOTOS_PREFETCHED:
//TODO ask password if hidden
new Thread(new Runnable() {
@Override
public void run() {
getAlbums().loadAlbums(getApplicationContext(), getAlbum().isHidden());
}
}).start();
displayCurrentAlbumMedia(false);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(false);
return true;
}
}
displayAlbums(true);
return false;
}
private void initUI() {
/**** TOOLBAR ****/
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**** RECYCLER VIEW ****/
rvAlbums = (RecyclerView) findViewById(R.id.grid_albums);
rvMedia = ((RecyclerView) findViewById(R.id.grid_photos));
rvAlbums.setHasFixedSize(true);
rvAlbums.setItemAnimator(new DefaultItemAnimator());
rvMedia.setHasFixedSize(true);
rvMedia.setItemAnimator(new DefaultItemAnimator());
albumsAdapter = new AlbumsAdapter(getAlbums().dispAlbums, LFMainActivity.this);
albumsAdapter.setOnClickListener(albumOnClickListener);
albumsAdapter.setOnLongClickListener(albumOnLongCLickListener);
rvAlbums.setAdapter(albumsAdapter);
mediaAdapter = new MediaAdapter(getAlbum().getMedia(), LFMainActivity.this);
mediaAdapter.setOnClickListener(photosOnClickListener);
mediaAdapter.setOnLongClickListener(photosOnLongClickListener);
rvMedia.setAdapter(mediaAdapter);
int spanCount = SP.getInt("n_columns_folders", 2);
rvAlbumsDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvAlbums.addItemDecoration(rvAlbumsDecoration);
rvAlbums.setLayoutManager(new GridLayoutManager(this, spanCount));
spanCount = SP.getInt("n_columns_media", 3);
rvMediaDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvMedia.setLayoutManager(new GridLayoutManager(getApplicationContext(), spanCount));
rvMedia.addItemDecoration(rvMediaDecoration);
/**** SWIPE TO REFRESH ****/
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeColors(getAccentColor());
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getBackgroundColor());
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (albumsMode) {
getAlbums().clearSelectedAlbums();
new PrepareAlbumTask().execute();
} else {
if (!all_photos) {
getAlbum().clearSelectedPhotos();
new PreparePhotosTask().execute();
} else {
new PrepareAllPhotos().execute();
}
}
}
});
/**** DRAWER ****/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.addDrawerListener(new ActionBarDrawerToggle(this,
mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
//Put your code here
// materialMenu.animateIconState(MaterialMenuDrawable.IconState.BURGER);
}
public void onDrawerOpened(View drawerView) {
//Put your code here
//materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW);
}
});
setRecentApp(getString(R.string.app_name));
setupUI();
if (pickMode){
hideNavigationBar();
swipeRefreshLayout.setPadding(0,0,0,0);
}
}
private void updateColumnsRvs() {
updateColumnsRvAlbums();
updateColumnsRvMedia();
}
private void updateColumnsRvAlbums() {
int spanCount = SP.getInt("n_columns_folders", 2);
if (spanCount != ((GridLayoutManager) rvAlbums.getLayoutManager()).getSpanCount()) {
rvAlbums.removeItemDecoration(rvAlbumsDecoration);
rvAlbumsDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvAlbums.addItemDecoration(rvAlbumsDecoration);
rvAlbums.setLayoutManager(new GridLayoutManager(this, spanCount));
}
}
private void updateColumnsRvMedia() {
int spanCount = SP.getInt("n_columns_media", 3);
if (spanCount != ((GridLayoutManager) rvMedia.getLayoutManager()).getSpanCount()) {
((GridLayoutManager) rvMedia.getLayoutManager()).getSpanCount();
rvMedia.removeItemDecoration(rvMediaDecoration);
rvMediaDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvMedia.setLayoutManager(new GridLayoutManager(getApplicationContext(), spanCount));
rvMedia.addItemDecoration(rvMediaDecoration);
}
}
//region TESTING
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public final void onActivityResult(final int requestCode, final int resultCode, final Intent resultData) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_SD_CARD_PERMISSIONS) {
Uri treeUri = resultData.getData();
// Persist URI in shared preference so that you can use it later.
ContentHelper.saveSdCardInfo(getApplicationContext(), treeUri);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Toast.makeText(this, R.string.got_permission_wr_sdcard, Toast.LENGTH_SHORT).show();
}
}
}
//endregion
private void requestSdCardPermissions() {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(LFMainActivity.this, dialogBuilder,
R.string.sd_card_write_permission_title, R.string.sd_card_permissions_message);
dialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_CODE_SD_CARD_PERMISSIONS);
}
});
dialogBuilder.show();
}
//region UI/GRAPHIC
private void setupUI() {
updateColumnsRvs();
//TODO: MUST BE FIXED
toolbar.setPopupTheme(getPopupToolbarStyle());
toolbar.setBackgroundColor(getPrimaryColor());
/**** SWIPE TO REFRESH ****/
swipeRefreshLayout.setColorSchemeColors(getAccentColor());
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getBackgroundColor());
setStatusBarColor();
setNavBarColor();
setDrawerTheme();
rvAlbums.setBackgroundColor(getBackgroundColor());
rvMedia.setBackgroundColor(getBackgroundColor());
mediaAdapter.updatePlaceholder(getApplicationContext());
albumsAdapter.updateTheme();
/**** DRAWER ****/
setScrollViewColor((ScrollView) findViewById(R.id.drawer_scrollbar));
/**** recyclers drawable *****/
Drawable drawableScrollBar = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_scrollbar);
drawableScrollBar.setColorFilter(new PorterDuffColorFilter(getPrimaryColor(), PorterDuff.Mode.SRC_ATOP));
}
private void setDrawerTheme() {
findViewById(R.id.Drawer_Header).setBackgroundColor(getPrimaryColor());
findViewById(R.id.Drawer_Body).setBackgroundColor(getDrawerBackground());
findViewById(R.id.drawer_scrollbar).setBackgroundColor(getDrawerBackground());
findViewById(R.id.Drawer_Body_Divider).setBackgroundColor(getIconColor());
/** TEXT VIEWS **/
int color = getTextColor();
((TextView) findViewById(R.id.Drawer_Default_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_Setting_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_About_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_hidden_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_share_Item)).setTextColor(color);
/** ICONS **/
color = getIconColor();
((IconicsImageView) findViewById(R.id.Drawer_Default_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_Setting_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_About_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_hidden_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_share_Icon)).setColor(color);
findViewById(R.id.ll_drawer_Setting).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LFMainActivity.this, SettingsActivity.class);
mDrawerLayout.closeDrawer(GravityCompat.START);
startActivity(intent);
}
});
findViewById(R.id.ll_drawer_About).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LFMainActivity.this, AboutActivity.class);
mDrawerLayout.closeDrawer(GravityCompat.START);
startActivity(intent);
}
});
findViewById(R.id.ll_drawer_Default).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hidden = false;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask().execute();
}
});
findViewById(R.id.ll_drawer_hidden).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.isActiveSecurity() && securityObj.isPasswordOnHidden()) {
AlertDialog.Builder passwordDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword = securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.show();
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View
.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
hidden = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask().execute();
passwordDialog.dismiss();
} else {
Toast.makeText(getApplicationContext(), R.string.wrong_password, Toast.LENGTH_SHORT).show();
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else {
hidden = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask().execute();
}
}
});
findViewById(R.id.ll_share_phimpme).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onInviteClicked();
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
}
private void onInviteClicked() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.install_phimpme) + "\n "+ getString(R.string.invitation_deep_link));
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
//endregion
private void updateSelectedStuff() {
if (albumsMode) {
if (editMode)
toolbar.setTitle(getAlbums().getSelectedCount() + "/" + getAlbums().dispAlbums.size());
else {
toolbar.setTitle(getString(R.string.app_name));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_menu));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
} else {
if (editMode)
if (!all_photos)
toolbar.setTitle(getAlbum().getSelectedCount() + "/" + getAlbum().getMedia().size());
else toolbar.setTitle(selectedMedias.size() + "/" + size);
else {
if (!all_photos)
toolbar.setTitle(getAlbum().getName());
else toolbar.setTitle(getString(R.string.all_media));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
}
}
if (editMode) {
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_check));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finishEditMode();
clearSelectedPhotos();
}
});
}
}
//called from onBackPressed()
private void finishEditMode() {
editMode = false;
if (albumsMode) {
getAlbums().clearSelectedAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
getAlbum().clearSelectedPhotos();
mediaAdapter.notifyDataSetChanged();
}
invalidateOptionsMenu();
}
private void checkNothing() {
TextView a = (TextView) findViewById(R.id.nothing_to_show);
a.setTextColor(getTextColor());
a.setVisibility((albumsMode && getAlbums().dispAlbums.size() == 0) || (!albumsMode && getAlbum().getMedia().size() == 0) ? View.VISIBLE : View.GONE);
}
//region MENU
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_albums, menu);
if (albumsMode) {
Drawable shareIcon = getResources().getDrawable(R.drawable.ic_photo_24dp, getTheme());
shareIcon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
menu.findItem(R.id.all_photos).setIcon(shareIcon);
menu.findItem(R.id.select_all).setTitle(
getString(getAlbums().getSelectedCount() == albumsAdapter.getItemCount()
? R.string.clear_selected
: R.string.select_all));
menu.findItem(R.id.ascending_sort_action).setChecked(getAlbums().getSortingOrder() == SortingOrder.ASCENDING);
switch (getAlbums().getSortingMode()) {
case NAME:
menu.findItem(R.id.name_sort_action).setChecked(true);
break;
case SIZE:
menu.findItem(R.id.size_sort_action).setChecked(true);
break;
case DATE:
default:
menu.findItem(R.id.date_taken_sort_action).setChecked(true);
break;
case NUMERIC:
menu.findItem(R.id.numeric_sort_action).setChecked(true);
break;
}
} else {
menu.findItem(R.id.select_all).setTitle(getString(
getAlbum().getSelectedCount() == mediaAdapter.getItemCount()
|| selectedMedias.size() == size
? R.string.clear_selected
: R.string.select_all));
menu.findItem(R.id.ascending_sort_action).setChecked(getAlbum().settings.getSortingOrder() == SortingOrder.ASCENDING);
switch (getAlbum().settings.getSortingMode()) {
case NAME:
menu.findItem(R.id.name_sort_action).setChecked(true);
break;
case SIZE:
menu.findItem(R.id.size_sort_action).setChecked(true);
break;
case TYPE:
menu.findItem(R.id.type_sort_action).setChecked(true);
break;
case DATE:
default:
menu.findItem(R.id.date_taken_sort_action).setChecked(true);
break;
case NUMERIC:
menu.findItem(R.id.numeric_sort_action).setChecked(true);
break;
}
}
menu.findItem(R.id.hideAlbumButton).setTitle(hidden ? getString(R.string.unhide) : getString(R.string.hide));
menu.findItem(R.id.delete_action).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_delete));
menu.findItem(R.id.sort_action).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_sort));
menu.findItem(R.id.sharePhotos).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_share));
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
if (albumsMode) {
editMode = getAlbums().getSelectedCount() != 0;
menu.setGroupVisible(R.id.album_options_menu, editMode);
menu.setGroupVisible(R.id.photos_option_men, false);
menu.findItem(R.id.all_photos).setVisible(true);
} else {
if (!all_photos) {
editMode = getAlbum().areMediaSelected();
menu.setGroupVisible(R.id.photos_option_men, editMode);
menu.setGroupVisible(R.id.album_options_menu, !editMode);
menu.findItem(R.id.all_photos).setVisible(false);
} else {
editMode = selectedMedias.size() != 0 ? true : false;
menu.setGroupVisible(R.id.photos_option_men, editMode);
menu.setGroupVisible(R.id.album_options_menu, !editMode);
menu.findItem(R.id.all_photos).setVisible(false);
}
}
togglePrimaryToolbarOptions(menu);
updateSelectedStuff();
menu.findItem(R.id.action_copy).setVisible(!all_photos);
menu.findItem(R.id.action_move).setVisible(!all_photos);
menu.findItem(R.id.excludeAlbumButton).setVisible(editMode && !all_photos);
menu.findItem(R.id.select_all).setVisible(editMode);
menu.findItem(R.id.type_sort_action).setVisible(!albumsMode);
menu.findItem(R.id.delete_action).setVisible((!albumsMode || editMode));
menu.findItem(R.id.hideAlbumButton).setVisible(!all_photos);
menu.findItem(R.id.clear_album_preview).setVisible(!albumsMode && getAlbum().hasCustomCover());
menu.findItem(R.id.renameAlbum).setVisible(((albumsMode && getAlbums().getSelectedCount() == 1) || (!albumsMode && !editMode)) && !all_photos);
if (getAlbums().getSelectedCount() == 1)
menu.findItem(R.id.set_pin_album).setTitle(getAlbums().getSelectedAlbum(0).isPinned() ? getString(R.string.un_pin) : getString(R.string.pin));
menu.findItem(R.id.set_pin_album).setVisible(albumsMode && getAlbums().getSelectedCount() == 1);
menu.findItem(R.id.setAsAlbumPreview).setVisible(!albumsMode && !all_photos);
menu.findItem(R.id.affixPhoto).setVisible(!albumsMode && (getAlbum().getSelectedCount() > 1) || selectedMedias.size() > 1);
return super.onPrepareOptionsMenu(menu);
}
private void togglePrimaryToolbarOptions(final Menu menu) {
menu.setGroupVisible(R.id.general_action, !editMode);
}
//endregion
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.all_photos:
if (!all_photos) {
all_photos = true;
displayAllMedia(true);
} else {
displayAlbums();
}
return true;
case R.id.select_all:
if (albumsMode) {
//if all albums are already selected, unselect all of them
if (getAlbums().getSelectedCount() == albumsAdapter.getItemCount()) {
editMode = false;
getAlbums().clearSelectedAlbums();
}
// else, select all albums
else getAlbums().selectAllAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
if (!all_photos) {
//if all photos are already selected, unselect all of them
if (getAlbum().getSelectedCount() == mediaAdapter.getItemCount()) {
editMode = false;
getAlbum().clearSelectedPhotos();
}
// else, select all photos
else getAlbum().selectAllPhotos();
mediaAdapter.notifyDataSetChanged();
} else {
if (selectedMedias.size() == size) {
editMode = false;
clearSelectedPhotos();
}
// else, select all photos
else {
clearSelectedPhotos();
selectAllPhotos();
}
mediaAdapter.notifyDataSetChanged();
}
}
invalidateOptionsMenu();
return true;
case R.id.set_pin_album:
getAlbums().getSelectedAlbum(0).settings.togglePin(getApplicationContext());
getAlbums().sortAlbums(getApplicationContext());
getAlbums().clearSelectedAlbums();
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
invalidateOptionsMenu();
return true;
case R.id.settings:
startActivity(new Intent(LFMainActivity.this, SettingsActivity.class));
return true;
case R.id.hideAlbumButton:
final AlertDialog.Builder hideDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(LFMainActivity.this, hideDialogBuilder,
hidden ? R.string.unhide : R.string.hide,
hidden ? R.string.unhide_album_message : R.string.hide_album_message);
hideDialogBuilder.setPositiveButton(getString(hidden ? R.string.unhide : R.string.hide).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (albumsMode) {
if (hidden) getAlbums().unHideSelectedAlbums(getApplicationContext());
else getAlbums().hideSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
if (hidden)
getAlbums().unHideAlbum(getAlbum().getPath(), getApplicationContext());
else
getAlbums().hideAlbum(getAlbum().getPath(), getApplicationContext());
displayAlbums(true);
}
}
});
if (!hidden) {
hideDialogBuilder.setNeutralButton(this.getString(R.string.exclude).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (albumsMode) {
getAlbums().excludeSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
customAlbumsHelper.excludeAlbum(getAlbum().getPath());
displayAlbums(true);
}
}
});
}
hideDialogBuilder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
hideDialogBuilder.show();
return true;
case R.id.delete_action:
class DeletePhotos extends AsyncTask<String, Integer, Boolean> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
//if in album mode, delete selected albums
if (albumsMode)
return getAlbums().deleteSelectedAlbums(LFMainActivity.this);
else {
// if in selection mode, delete selected media
if (editMode && !all_photos)
return getAlbum().deleteSelectedMedia(getApplicationContext());
else if (all_photos) {
Boolean succ = false;
for (Media media : selectedMedias) {
String[] projection = {MediaStore.Images.Media._ID};
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[]{media.getPath()};
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
contentResolver.delete(deleteUri, null, null);
succ = true;
} else {
succ = false;
// File not found in media store DB
}
c.close();
}
return succ;
}
// if not in selection mode, delete current album entirely
else {
boolean succ = getAlbums().deleteAlbum(getAlbum(), getApplicationContext());
getAlbum().getMedia().clear();
return succ;
}
}
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
// in albumsMode, the selected albums have been deleted.
if (albumsMode) {
getAlbums().clearSelectedAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
if (!all_photos) {
//if all media in current album have been deleted, delete current album too.
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
} else
mediaAdapter.swapDataSet(getAlbum().getMedia());
} else {
clearSelectedPhotos();
listAll = StorageProvider.getAllShownImages(LFMainActivity.this);
media = listAll;
size = listAll.size();
mediaAdapter.swapDataSet(listAll);
}
}
} else requestSdCardPermissions();
invalidateOptionsMenu();
checkNothing();
swipeRefreshLayout.setRefreshing(false);
}
}
AlertDialog.Builder deleteDialog = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(this, deleteDialog, R.string.delete, albumsMode || !editMode ? R.string.delete_album_message : R.string.delete_photos_message);
deleteDialog.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
deleteDialog.setPositiveButton(this.getString(R.string.delete).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (securityObj.isActiveSecurity() && securityObj.isPasswordOnDelete()) {
AlertDialog.Builder passwordDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword = securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should br empty it will be overwrite later
//to avoid dismiss of the dialog on wrong password
}
});
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.show();
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if password is correct, call DeletePhotos and perform deletion
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
passwordDialog.dismiss();
new DeletePhotos().execute();
}
// if password is incorrect, don't delete and notify user of incorrect password
else {
Toast.makeText(getApplicationContext(), R.string.wrong_password, Toast.LENGTH_SHORT).show();
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else new DeletePhotos().execute();
}
});
deleteDialog.show();
return true;
case R.id.excludeAlbumButton:
final AlertDialog.Builder excludeDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final View excludeDialogLayout = getLayoutInflater().inflate(R.layout.dialog_exclude, null);
TextView textViewExcludeTitle = (TextView) excludeDialogLayout.findViewById(R.id.text_dialog_title);
TextView textViewExcludeMessage = (TextView) excludeDialogLayout.findViewById(R.id.text_dialog_message);
final Spinner spinnerParents = (Spinner) excludeDialogLayout.findViewById(R.id.parents_folder);
spinnerParents.getBackground().setColorFilter(getIconColor(), PorterDuff.Mode.SRC_ATOP);
((CardView) excludeDialogLayout.findViewById(R.id.message_card)).setCardBackgroundColor(getCardBackgroundColor());
textViewExcludeTitle.setBackgroundColor(getPrimaryColor());
textViewExcludeTitle.setText(getString(R.string.exclude));
if ((albumsMode && getAlbums().getSelectedCount() > 1)) {
textViewExcludeMessage.setText(R.string.exclude_albums_message);
spinnerParents.setVisibility(View.GONE);
} else {
textViewExcludeMessage.setText(R.string.exclude_album_message);
spinnerParents.setAdapter(getSpinnerAdapter(albumsMode ? getAlbums().getSelectedAlbum(0).getParentsFolders() : getAlbum().getParentsFolders()));
}
textViewExcludeMessage.setTextColor(getTextColor());
excludeDialogBuilder.setView(excludeDialogLayout);
excludeDialogBuilder.setPositiveButton(this.getString(R.string.exclude).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if ((albumsMode && getAlbums().getSelectedCount() > 1)) {
getAlbums().excludeSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
customAlbumsHelper.excludeAlbum(spinnerParents.getSelectedItem().toString());
finishEditMode();
displayAlbums(true);
}
}
});
excludeDialogBuilder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
excludeDialogBuilder.show();
return true;
case R.id.sharePhotos:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.sent_to_action));
// list of all selected media in current album
ArrayList<Uri> files = new ArrayList<Uri>();
if (!all_photos) {
for (Media f : getAlbum().getSelectedMedia())
files.add(f.getUri());
} else {
for (Media f : selectedMedias)
files.add(f.getUri());
}
String extension = files.get(0).getPath().substring(files.get(0).getPath().lastIndexOf('.') + 1);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
if (!all_photos)
intent.setType(StringUtils.getGenericMIME(getAlbum().getSelectedMedia(0).getMimeType()));
else intent.setType(mimeType);
finishEditMode();
startActivity(Intent.createChooser(intent, getResources().getText(R.string.send_to)));
return true;
case R.id.name_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(NAME);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), NAME);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.date_taken_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(DATE);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), DATE);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.size_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(SIZE);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), SIZE);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.type_sort_action:
if (!albumsMode) {
getAlbum().setDefaultSortingMode(getApplicationContext(), TYPE);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
item.setChecked(true);
}
return true;
case R.id.numeric_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(NUMERIC);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), NUMERIC);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.ascending_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingAscending(item.isChecked() ? SortingOrder.DESCENDING : SortingOrder.ASCENDING);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingAscending(getApplicationContext(), item.isChecked() ? SortingOrder.DESCENDING : SortingOrder.ASCENDING);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(!item.isChecked());
return true;
//region Affix
case R.id.affixPhoto:
//region Async MediaAffix
class affixMedia extends AsyncTask<Affix.Options, Integer, Void> {
private AlertDialog dialog;
@Override
protected void onPreExecute() {
AlertDialog.Builder progressDialog = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
dialog = AlertDialogsHelper.getProgressDialog(LFMainActivity.this, progressDialog,
getString(R.string.affix), getString(R.string.affix_text));
dialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Affix.Options... arg0) {
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
if (!all_photos) {
for (int i = 0; i < getAlbum().getSelectedCount(); i++) {
bitmapArray.add(getBitmap(getAlbum().getSelectedMedia(i).getPath()));
}
} else {
for (int i = 0; i < selectedMedias.size(); i++) {
bitmapArray.add(getBitmap(selectedMedias.get(i).getPath()));
}
}
if (bitmapArray.size() > 1)
Affix.AffixBitmapList(getApplicationContext(), bitmapArray, arg0[0]);
else runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), R.string.affix_error, Toast.LENGTH_SHORT).show();
}
});
return null;
}
@Override
protected void onPostExecute(Void result) {
editMode = false;
if(!all_photos)
getAlbum().clearSelectedPhotos();
else clearSelectedPhotos();
dialog.dismiss();
invalidateOptionsMenu();
mediaAdapter.notifyDataSetChanged();
if(!all_photos)
new PreparePhotosTask().execute();
else clearSelectedPhotos();
}
}
//endregion
final AlertDialog.Builder builder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final View dialogLayout = getLayoutInflater().inflate(R.layout.dialog_affix, null);
dialogLayout.findViewById(R.id.affix_title).setBackgroundColor(getPrimaryColor());
((CardView) dialogLayout.findViewById(R.id.affix_card)).setCardBackgroundColor(getCardBackgroundColor());
//ITEMS
final SwitchCompat swVertical = (SwitchCompat) dialogLayout.findViewById(R.id.affix_vertical_switch);
final SwitchCompat swSaveHere = (SwitchCompat) dialogLayout.findViewById(R.id.save_here_switch);
final RadioGroup radioFormatGroup = (RadioGroup) dialogLayout.findViewById(R.id.radio_format);
final TextView txtQuality = (TextView) dialogLayout.findViewById(R.id.affix_quality_title);
final SeekBar seekQuality = (SeekBar) dialogLayout.findViewById(R.id.seek_bar_quality);
//region THEME STUFF
setScrollViewColor((ScrollView) dialogLayout.findViewById(R.id.affix_scrollView));
/** TextViews **/
int color = getTextColor();
((TextView) dialogLayout.findViewById(R.id.affix_vertical_title)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.compression_settings_title)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.save_here_title)).setTextColor(color);
/** Sub TextViews **/
color = getTextColor();
((TextView) dialogLayout.findViewById(R.id.save_here_sub)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.affix_vertical_sub)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.affix_format_sub)).setTextColor(color);
txtQuality.setTextColor(color);
/** Icons **/
color = getIconColor();
((IconicsImageView) dialogLayout.findViewById(R.id.affix_quality_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.affix_format_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.affix_vertical_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.save_here_icon)).setColor(color);
seekQuality.getProgressDrawable().setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));
seekQuality.getThumb().setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_jpeg));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_png));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_webp));
updateSwitchColor(swVertical, getAccentColor());
updateSwitchColor(swSaveHere, getAccentColor());
//endregion
seekQuality.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
txtQuality.setText(Html.fromHtml(
String.format(Locale.getDefault(), "%s <b>%d</b>", getString(R.string.quality), progress)));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekQuality.setProgress(90); //DEFAULT
swVertical.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateSwitchColor(swVertical, getAccentColor());
}
});
swSaveHere.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateSwitchColor(swSaveHere, getAccentColor());
}
});
builder.setView(dialogLayout);
builder.setPositiveButton(this.getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Bitmap.CompressFormat compressFormat;
switch (radioFormatGroup.getCheckedRadioButtonId()) {
case R.id.radio_jpeg:
default:
compressFormat = Bitmap.CompressFormat.JPEG;
break;
case R.id.radio_png:
compressFormat = Bitmap.CompressFormat.PNG;
break;
case R.id.radio_webp:
compressFormat = Bitmap.CompressFormat.WEBP;
break;
}
Affix.Options options = new Affix.Options(
swSaveHere.isChecked() ? getAlbum().getPath() : Affix.getDefaultDirectoryPath(),
compressFormat,
seekQuality.getProgress(),
swVertical.isChecked());
new affixMedia().execute(options);
}
});
builder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
builder.show();
return true;
//endregion
case R.id.action_move:
bottomSheetDialogFragment = new SelectAlbumBottomSheet();
bottomSheetDialogFragment.setTitle(getString(R.string.move_to));
bottomSheetDialogFragment.setSelectAlbumInterface(new SelectAlbumBottomSheet.SelectAlbumInterface() {
@Override
public void folderSelected(String path) {
swipeRefreshLayout.setRefreshing(true);
if (getAlbum().moveSelectedMedia(getApplicationContext(), path) > 0) {
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
}
mediaAdapter.swapDataSet(getAlbum().getMedia());
finishEditMode();
invalidateOptionsMenu();
} else requestSdCardPermissions();
swipeRefreshLayout.setRefreshing(false);
bottomSheetDialogFragment.dismiss();
}
});
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
return true;
case R.id.action_copy:
bottomSheetDialogFragment = new SelectAlbumBottomSheet();
bottomSheetDialogFragment.setTitle(getString(R.string.copy_to));
bottomSheetDialogFragment.setSelectAlbumInterface(new SelectAlbumBottomSheet.SelectAlbumInterface() {
@Override
public void folderSelected(String path) {
boolean success = getAlbum().copySelectedPhotos(getApplicationContext(), path);
finishEditMode();
bottomSheetDialogFragment.dismiss();
if (!success)
requestSdCardPermissions();
}
});
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
return true;
case R.id.renameAlbum:
AlertDialog.Builder renameDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextNewName = new EditText(getApplicationContext());
editTextNewName.setText(albumsMode ? getAlbums().getSelectedAlbum(0).getName() : getAlbum().getName());
AlertDialogsHelper.getInsertTextDialog(LFMainActivity.this, renameDialogBuilder,
editTextNewName, R.string.rename_album);
renameDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
renameDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should br empty it will be overwrite later
//to avoid dismiss of the dialog
}
});
final AlertDialog renameDialog = renameDialogBuilder.create();
renameDialog.show();
renameDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View dialog) {
if (editTextNewName.length() != 0) {
swipeRefreshLayout.setRefreshing(true);
boolean success = false;
if (albumsMode) {
int index = getAlbums().dispAlbums.indexOf(getAlbums().getSelectedAlbum(0));
getAlbums().getAlbum(index).updatePhotos(getApplicationContext());
success = getAlbums().getAlbum(index).renameAlbum(getApplicationContext(),
editTextNewName.getText().toString());
albumsAdapter.notifyItemChanged(index);
} else {
success = getAlbum().renameAlbum(getApplicationContext(), editTextNewName.getText().toString());
toolbar.setTitle(getAlbum().getName());
mediaAdapter.notifyDataSetChanged();
}
renameDialog.dismiss();
if (success){
Snackbar.make(getWindow().getDecorView().getRootView(),
getString(R.string.rename_succes),Snackbar.LENGTH_LONG).show();
}else {
Snackbar.make(getWindow().getDecorView().getRootView(),
getString(R.string.rename_error),Snackbar.LENGTH_LONG)
.show();
requestSdCardPermissions();
}
swipeRefreshLayout.setRefreshing(false);
} else {
StringUtils.showToast(getApplicationContext(), getString(R.string.insert_something));
editTextNewName.requestFocus();
}
}
});
return true;
case R.id.clear_album_preview:
if (!albumsMode) {
getAlbum().removeCoverAlbum(getApplicationContext());
}
return true;
case R.id.setAsAlbumPreview:
if (!albumsMode) {
getAlbum().setSelectedPhotoAsPreview(getApplicationContext());
finishEditMode();
}
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap bitmap = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = bitmap.getHeight();
int width = bitmap.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) x,
(int) y, true);
bitmap.recycle();
bitmap = scaledBitmap;
System.gc();
} else {
bitmap = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " +bitmap.getWidth() + ", height: " +
bitmap.getHeight());
return bitmap;
} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;
}
}
/**
* If we are in albumsMode, make the albums recyclerView visible. If we are not, make media recyclerView visible.
* @param albumsMode it indicates whether we are in album selection mode or not
*/
private void toggleRecyclersVisibility(boolean albumsMode) {
rvAlbums.setVisibility(albumsMode ? View.VISIBLE : View.GONE);
rvMedia.setVisibility(albumsMode ? View.GONE : View.VISIBLE);
//touchScrollBar.setScrollBarHidden(albumsMode);
}
/**
* handles back presses.
* If we are currently in selection mode, back press will take us out of selection mode.
* If we are not in selection mode but in albumsMode and the drawer is open, back press will close it.
* If we are not in selection mode but in albumsMode and the drawer is closed, finish the activity.
* If we are neither in selection mode nor in albumsMode, display the albums again.
*/
@Override
public void onBackPressed() {
if (editMode) finishEditMode();
else {
if (albumsMode) {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
mDrawerLayout.closeDrawer(GravityCompat.START);
else finish();
} else {
displayAlbums();
setRecentApp(getString(R.string.app_name));
}
}
}
private class PrepareAlbumTask extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
toggleRecyclersVisibility(true);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
getAlbums().loadAlbums(getApplicationContext(), hidden);
return null;
}
@Override
protected void onPostExecute(Void result) {
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
checkNothing();
swipeRefreshLayout.setRefreshing(false);
getAlbums().saveBackup(getApplicationContext());
invalidateOptionsMenu();
finishEditMode();
}
}
private class PreparePhotosTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
toggleRecyclersVisibility(false);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
getAlbum().updatePhotos(getApplicationContext());
return null;
}
@Override
protected void onPostExecute(Void result) {
mediaAdapter.swapDataSet(getAlbum().getMedia());
if (!hidden)
HandlingAlbums.addAlbumToBackup(getApplicationContext(), getAlbum());
checkNothing();
swipeRefreshLayout.setRefreshing(false);
invalidateOptionsMenu();
finishEditMode();
}
}
private class PrepareAllPhotos extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
toggleRecyclersVisibility(false);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
getAlbum().updatePhotos(getApplicationContext());
return null;
}
@Override
protected void onPostExecute(Void result) {
mediaAdapter.swapDataSet(StorageProvider.getAllShownImages(LFMainActivity.this));
if (!hidden)
HandlingAlbums.addAlbumToBackup(getApplicationContext(), getAlbum());
checkNothing();
swipeRefreshLayout.setRefreshing(false);
invalidateOptionsMenu();
finishEditMode();
toolbar.setTitle(getString(R.string.all_media));
clearSelectedPhotos();
}
}
/*private class MovePhotos extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
boolean success = true;
try
{
for (int i = 0; i < getAlbum().selectedMedias.size(); i++) {
File from = new File(getAlbum().selectedMedias.get(i).getPath());
File to = new File(StringUtils.getPhotoPathMoved(getAlbum().selectedMedias.get(i).getPath(), arg0[0]));
if (ContentHelper.moveFile(getApplicationContext(), from, to)) {
MediaScannerConnection.scanFile(getApplicationContext(),
new String[]{ to.getAbsolutePath(), from.getAbsolutePath() }, null, null);
getAlbum().getMedia().remove(getAlbum().selectedMedias.get(i));
} else success = false;
}
} catch (Exception e) { e.printStackTrace(); }
return success;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
}
} else requestSdCardPermissions();
mediaAdapter.swapDataSet(getAlbum().getMedia());
finishEditMode();
invalidateOptionsMenu();
swipeRefreshLayout.setRefreshing(false);
}
}*/
}
|
app/src/main/java/org/fossasia/phimpme/leafpic/activities/LFMainActivity.java
|
package org.fossasia.phimpme.leafpic.activities;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.view.IconicsImageView;
import org.fossasia.phimpme.R;
import org.fossasia.phimpme.base.SharedMediaActivity;
import org.fossasia.phimpme.leafpic.SelectAlbumBottomSheet;
import org.fossasia.phimpme.leafpic.adapters.AlbumsAdapter;
import org.fossasia.phimpme.leafpic.adapters.MediaAdapter;
import org.fossasia.phimpme.leafpic.data.Album;
import org.fossasia.phimpme.leafpic.data.CustomAlbumsHelper;
import org.fossasia.phimpme.leafpic.data.HandlingAlbums;
import org.fossasia.phimpme.leafpic.data.Media;
import org.fossasia.phimpme.leafpic.data.base.FilterMode;
import org.fossasia.phimpme.leafpic.data.base.SortingOrder;
import org.fossasia.phimpme.leafpic.data.providers.StorageProvider;
import org.fossasia.phimpme.leafpic.util.Affix;
import org.fossasia.phimpme.leafpic.util.AlertDialogsHelper;
import org.fossasia.phimpme.leafpic.util.ContentHelper;
import org.fossasia.phimpme.leafpic.util.Measure;
import org.fossasia.phimpme.leafpic.util.PreferenceUtil;
import org.fossasia.phimpme.leafpic.util.SecurityHelper;
import org.fossasia.phimpme.leafpic.util.StringUtils;
import org.fossasia.phimpme.leafpic.views.GridSpacingItemDecoration;
import org.fossasia.phimpme.utilities.ActivitySwitchHelper;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.DATE;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.NAME;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.NUMERIC;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.SIZE;
import static org.fossasia.phimpme.leafpic.data.base.SortingMode.TYPE;
public class LFMainActivity extends SharedMediaActivity {
private static String TAG = "AlbumsAct";
private int REQUEST_CODE_SD_CARD_PERMISSIONS = 42;
private CustomAlbumsHelper customAlbumsHelper = CustomAlbumsHelper.getInstance(LFMainActivity.this);
private PreferenceUtil SP;
private SecurityHelper securityObj;
private RecyclerView rvAlbums;
private AlbumsAdapter albumsAdapter;
private GridSpacingItemDecoration rvAlbumsDecoration;
private RecyclerView rvMedia;
private MediaAdapter mediaAdapter;
private GridSpacingItemDecoration rvMediaDecoration;
private DrawerLayout mDrawerLayout;
private Toolbar toolbar;
private SelectAlbumBottomSheet bottomSheetDialogFragment;
private SwipeRefreshLayout swipeRefreshLayout;
private boolean hidden = false, pickMode = false, editMode = false, albumsMode = true, firstLaunch = true;
//To handle all photos/Album conditions
public boolean all_photos = false;
final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
public static ArrayList<Media> listAll;
public int size;
public int pos;
private ArrayList<Media> media;
private ArrayList<Media> selectedMedias = new ArrayList<>();
/*
editMode- When true, user can select items by clicking on them one by one
*/
/**
* Handles long clicks on photos.
* If first long click on photo (editMode = false), go into selection mode and set editMode = true.
* If not first long click, means that already in selection mode- s0 select all photos upto chosen one.
*/
private View.OnLongClickListener photosOnLongClickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Media m = (Media) v.findViewById(R.id.photo_path).getTag();
//If first long press, turn on selection mode
if (!all_photos) {
if (!editMode) {
mediaAdapter.notifyItemChanged(getAlbum().toggleSelectPhoto(m));
editMode = true;
} else
getAlbum().selectAllPhotosUpTo(getAlbum().getIndex(m), mediaAdapter);
invalidateOptionsMenu();
} else
if(!editMode){
mediaAdapter.notifyItemChanged(toggleSelectPhoto(getImagePosition(m.getPath())));
editMode = true;
mediaAdapter.swapDataSet(listAll);
}
else selectAllPhotosUpTo(getImagePosition(m.getPath()),mediaAdapter);
return true;
}
};
private int toggleSelectPhoto(int index) {
if (media.get(index) != null) {
media.get(index).setSelected(!media.get(index).isSelected());
if (media.get(index).isSelected())
selectedMedias.add(media.get(index));
else
selectedMedias.remove(media.get(index));
}
if(selectedMedias.size()==0){
editMode = false;
toolbar.setTitle(getString(R.string.all));
}
else
toolbar.setTitle(selectedMedias.size() + "/" + size);
return index;
}
public void clearSelectedPhotos() {
for (Media m : media)
m.setSelected(false);
if (selectedMedias!=null)
selectedMedias.clear();
toolbar.setTitle(getString(R.string.all));
}
public void selectAllPhotosUpTo(int targetIndex, MediaAdapter adapter) {
int indexRightBeforeOrAfter = -1;
int indexNow;
for (Media sm : selectedMedias) {
indexNow = media.indexOf(sm);
if (indexRightBeforeOrAfter == -1) indexRightBeforeOrAfter = indexNow;
if (indexNow > targetIndex) break;
indexRightBeforeOrAfter = indexNow;
}
if (indexRightBeforeOrAfter != -1) {
for (int index = Math.min(targetIndex, indexRightBeforeOrAfter); index <= Math.max(targetIndex, indexRightBeforeOrAfter); index++) {
if (media.get(index) != null && !media.get(index).isSelected()) {
media.get(index).setSelected(true);
selectedMedias.add(media.get(index));
adapter.notifyItemChanged(index);
}
}
}
toolbar.setTitle(selectedMedias.size() + "/" + size);
}
/**
* Handles short clicks on photos.
* If in selection mode (editMode = true) , select the photo if it is unselected and unselect it if it's selected.
* This mechanism makes it possible to select photos one by one by short-clicking on them.
* If not in selection mode (editMode = false) , get current photo from album and open it in singleActivity
*/
private View.OnClickListener photosOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Media m = (Media) v.findViewById(R.id.photo_path).getTag();
if (all_photos) {
pos = getImagePosition(m.getPath());
}
if (!all_photos) {
if (!pickMode) {
//if in selection mode, toggle the selected/unselect state of photo
if (editMode) {
mediaAdapter.notifyItemChanged(getAlbum().toggleSelectPhoto(m));
invalidateOptionsMenu();
} else {
getAlbum().setCurrentPhotoIndex(m);
Intent intent = new Intent(LFMainActivity.this, SingleMediaActivity.class);
intent.putExtra("path",Uri.fromFile(new File(m.getPath())).toString());
intent.setAction(SingleMediaActivity.ACTION_OPEN_ALBUM);
startActivity(intent);
}
} else {
setResult(RESULT_OK, new Intent().setData(m.getUri()));
finish();
}
} else {
if(!editMode) {
Intent intent = new Intent(REVIEW_ACTION, Uri.fromFile(new File(m.getPath())));
intent.putExtra(getString(R.string.all_photo_mode), true);
intent.putExtra(getString(R.string.position), pos);
intent.putExtra(getString(R.string.allMediaSize), size);
intent.setClass(getApplicationContext(), SingleMediaActivity.class);
startActivity(intent);
}
else mediaAdapter.notifyItemChanged(toggleSelectPhoto(getImagePosition(m.getPath())));
}
}
};
private View.OnLongClickListener albumOnLongCLickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(((Album) v.findViewById(R.id.album_name).getTag())));
editMode = true;
invalidateOptionsMenu();
return true;
}
};
private View.OnClickListener albumOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Album album = (Album) v.findViewById(R.id.album_name).getTag();
//int index = Integer.parseInt(v.findViewById(R.id.album_name).getTag().toString());
if (editMode) {
albumsAdapter.notifyItemChanged(getAlbums().toggleSelectAlbum(album));
invalidateOptionsMenu();
} else {
getAlbums().setCurrentAlbum(album);
displayCurrentAlbumMedia(true);
setRecentApp(getAlbums().getCurrentAlbum().getName());
}
}
};
public int getImagePosition(String path) {
int pos = 0;
for (int i = 0; i < listAll.size(); i++) {
if (listAll.get(i).getPath().equals(path)) {
pos = i;
break;
}
}
return pos;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TAG","lfmain");
SP = PreferenceUtil.getInstance(getApplicationContext());
albumsMode = true;
editMode = false;
securityObj = new SecurityHelper(LFMainActivity.this);
if (getIntent().getExtras()!=null)
pickMode = getIntent().getExtras().getBoolean(SplashScreen.PICK_MODE);
listAll = StorageProvider.getAllShownImages(LFMainActivity.this);
size = listAll.size();
media = listAll;
initUI();
displayData(getIntent().getExtras());
}
@Override
public void onResume() {
super.onResume();
ActivitySwitchHelper.setContext(this);
securityObj.updateSecuritySetting();
setupUI();
getAlbums().clearSelectedAlbums();
getAlbum().clearSelectedPhotos();
if(all_photos)
mediaAdapter.swapDataSet(listAll);
if(!all_photos) {
if (SP.getBoolean("auto_update_media", false)) {
if (albumsMode) {
if (!firstLaunch) new PrepareAlbumTask().execute();
} else new PreparePhotosTask().execute();
} else {
albumsAdapter.notifyDataSetChanged();
mediaAdapter.notifyDataSetChanged();
}
}
invalidateOptionsMenu();
firstLaunch = false;
}
private void displayCurrentAlbumMedia(boolean reload) {
toolbar.setTitle(getAlbum().getName());
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mediaAdapter.swapDataSet(getAlbum().getMedia());
if (reload) new PreparePhotosTask().execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
albumsMode = editMode = false;
invalidateOptionsMenu();
}
private void displayAllMedia(boolean reload) {
clearSelectedPhotos();
toolbar.setTitle(getString(R.string.all_media));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mediaAdapter.swapDataSet(listAll);
if (reload) new PrepareAllPhotos().execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
albumsMode = editMode = false;
invalidateOptionsMenu();
}
private void displayAlbums() {
all_photos = false;
displayAlbums(true);
}
private void displayAlbums(boolean reload) {
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_menu));
toolbar.setTitle(getString(R.string.app_name));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
if (reload) new PrepareAlbumTask().execute();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
albumsMode = true;
editMode = false;
invalidateOptionsMenu();
mediaAdapter.swapDataSet(new ArrayList<Media>());
rvMedia.scrollToPosition(0);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private boolean displayData(Bundle data) {
if (data != null) {
switch (data.getInt(SplashScreen.CONTENT)) {
case SplashScreen.ALBUMS_PREFETCHED:
displayAlbums(false);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(true);
return true;
case SplashScreen.ALBUMS_BACKUP:
displayAlbums(true);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(true);
return true;
case SplashScreen.PHOTOS_PREFETCHED:
//TODO ask password if hidden
new Thread(new Runnable() {
@Override
public void run() {
getAlbums().loadAlbums(getApplicationContext(), getAlbum().isHidden());
}
}).start();
displayCurrentAlbumMedia(false);
// we pass the albumMode here . If true, show rvAlbum recyclerView. If false, show rvMedia recyclerView
toggleRecyclersVisibility(false);
return true;
}
}
displayAlbums(true);
return false;
}
private void initUI() {
/**** TOOLBAR ****/
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**** RECYCLER VIEW ****/
rvAlbums = (RecyclerView) findViewById(R.id.grid_albums);
rvMedia = ((RecyclerView) findViewById(R.id.grid_photos));
rvAlbums.setHasFixedSize(true);
rvAlbums.setItemAnimator(new DefaultItemAnimator());
rvMedia.setHasFixedSize(true);
rvMedia.setItemAnimator(new DefaultItemAnimator());
albumsAdapter = new AlbumsAdapter(getAlbums().dispAlbums, LFMainActivity.this);
albumsAdapter.setOnClickListener(albumOnClickListener);
albumsAdapter.setOnLongClickListener(albumOnLongCLickListener);
rvAlbums.setAdapter(albumsAdapter);
mediaAdapter = new MediaAdapter(getAlbum().getMedia(), LFMainActivity.this);
mediaAdapter.setOnClickListener(photosOnClickListener);
mediaAdapter.setOnLongClickListener(photosOnLongClickListener);
rvMedia.setAdapter(mediaAdapter);
int spanCount = SP.getInt("n_columns_folders", 2);
rvAlbumsDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvAlbums.addItemDecoration(rvAlbumsDecoration);
rvAlbums.setLayoutManager(new GridLayoutManager(this, spanCount));
spanCount = SP.getInt("n_columns_media", 3);
rvMediaDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvMedia.setLayoutManager(new GridLayoutManager(getApplicationContext(), spanCount));
rvMedia.addItemDecoration(rvMediaDecoration);
/**** SWIPE TO REFRESH ****/
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeColors(getAccentColor());
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getBackgroundColor());
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (albumsMode) {
getAlbums().clearSelectedAlbums();
new PrepareAlbumTask().execute();
} else {
if (!all_photos) {
getAlbum().clearSelectedPhotos();
new PreparePhotosTask().execute();
} else {
new PrepareAllPhotos().execute();
}
}
}
});
/**** DRAWER ****/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.addDrawerListener(new ActionBarDrawerToggle(this,
mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
//Put your code here
// materialMenu.animateIconState(MaterialMenuDrawable.IconState.BURGER);
}
public void onDrawerOpened(View drawerView) {
//Put your code here
//materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW);
}
});
setRecentApp(getString(R.string.app_name));
setupUI();
if (pickMode){
hideNavigationBar();
swipeRefreshLayout.setPadding(0,0,0,0);
}
}
private void updateColumnsRvs() {
updateColumnsRvAlbums();
updateColumnsRvMedia();
}
private void updateColumnsRvAlbums() {
int spanCount = SP.getInt("n_columns_folders", 2);
if (spanCount != ((GridLayoutManager) rvAlbums.getLayoutManager()).getSpanCount()) {
rvAlbums.removeItemDecoration(rvAlbumsDecoration);
rvAlbumsDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvAlbums.addItemDecoration(rvAlbumsDecoration);
rvAlbums.setLayoutManager(new GridLayoutManager(this, spanCount));
}
}
private void updateColumnsRvMedia() {
int spanCount = SP.getInt("n_columns_media", 3);
if (spanCount != ((GridLayoutManager) rvMedia.getLayoutManager()).getSpanCount()) {
((GridLayoutManager) rvMedia.getLayoutManager()).getSpanCount();
rvMedia.removeItemDecoration(rvMediaDecoration);
rvMediaDecoration = new GridSpacingItemDecoration(spanCount, Measure.pxToDp(3, getApplicationContext()), true);
rvMedia.setLayoutManager(new GridLayoutManager(getApplicationContext(), spanCount));
rvMedia.addItemDecoration(rvMediaDecoration);
}
}
//region TESTING
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public final void onActivityResult(final int requestCode, final int resultCode, final Intent resultData) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_SD_CARD_PERMISSIONS) {
Uri treeUri = resultData.getData();
// Persist URI in shared preference so that you can use it later.
ContentHelper.saveSdCardInfo(getApplicationContext(), treeUri);
getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Toast.makeText(this, R.string.got_permission_wr_sdcard, Toast.LENGTH_SHORT).show();
}
}
}
//endregion
private void requestSdCardPermissions() {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(LFMainActivity.this, dialogBuilder,
R.string.sd_card_write_permission_title, R.string.sd_card_permissions_message);
dialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_CODE_SD_CARD_PERMISSIONS);
}
});
dialogBuilder.show();
}
//region UI/GRAPHIC
private void setupUI() {
updateColumnsRvs();
//TODO: MUST BE FIXED
toolbar.setPopupTheme(getPopupToolbarStyle());
toolbar.setBackgroundColor(getPrimaryColor());
/**** SWIPE TO REFRESH ****/
swipeRefreshLayout.setColorSchemeColors(getAccentColor());
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getBackgroundColor());
setStatusBarColor();
setNavBarColor();
setDrawerTheme();
rvAlbums.setBackgroundColor(getBackgroundColor());
rvMedia.setBackgroundColor(getBackgroundColor());
mediaAdapter.updatePlaceholder(getApplicationContext());
albumsAdapter.updateTheme();
/**** DRAWER ****/
setScrollViewColor((ScrollView) findViewById(R.id.drawer_scrollbar));
/**** recyclers drawable *****/
Drawable drawableScrollBar = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_scrollbar);
drawableScrollBar.setColorFilter(new PorterDuffColorFilter(getPrimaryColor(), PorterDuff.Mode.SRC_ATOP));
}
private void setDrawerTheme() {
findViewById(R.id.Drawer_Header).setBackgroundColor(getPrimaryColor());
findViewById(R.id.Drawer_Body).setBackgroundColor(getDrawerBackground());
findViewById(R.id.drawer_scrollbar).setBackgroundColor(getDrawerBackground());
findViewById(R.id.Drawer_Body_Divider).setBackgroundColor(getIconColor());
/** TEXT VIEWS **/
int color = getTextColor();
((TextView) findViewById(R.id.Drawer_Default_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_Setting_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_About_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_hidden_Item)).setTextColor(color);
((TextView) findViewById(R.id.Drawer_share_Item)).setTextColor(color);
/** ICONS **/
color = getIconColor();
((IconicsImageView) findViewById(R.id.Drawer_Default_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_Setting_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_About_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_hidden_Icon)).setColor(color);
((IconicsImageView) findViewById(R.id.Drawer_share_Icon)).setColor(color);
findViewById(R.id.ll_drawer_Setting).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LFMainActivity.this, SettingsActivity.class);
mDrawerLayout.closeDrawer(GravityCompat.START);
startActivity(intent);
}
});
findViewById(R.id.ll_drawer_About).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LFMainActivity.this, AboutActivity.class);
mDrawerLayout.closeDrawer(GravityCompat.START);
startActivity(intent);
}
});
findViewById(R.id.ll_drawer_Default).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hidden = false;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask().execute();
}
});
findViewById(R.id.ll_drawer_hidden).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.isActiveSecurity() && securityObj.isPasswordOnHidden()) {
AlertDialog.Builder passwordDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword = securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.show();
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View
.OnClickListener() {
@Override
public void onClick(View v) {
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
hidden = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask().execute();
passwordDialog.dismiss();
} else {
Toast.makeText(getApplicationContext(), R.string.wrong_password, Toast.LENGTH_SHORT).show();
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else {
hidden = true;
mDrawerLayout.closeDrawer(GravityCompat.START);
new PrepareAlbumTask().execute();
}
}
});
findViewById(R.id.ll_share_phimpme).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onInviteClicked();
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
}
private void onInviteClicked() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.install_phimpme) + "\n "+ getString(R.string.invitation_deep_link));
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
//endregion
private void updateSelectedStuff() {
if (albumsMode) {
if (editMode)
toolbar.setTitle(getAlbums().getSelectedCount() + "/" + getAlbums().dispAlbums.size());
else {
toolbar.setTitle(getString(R.string.app_name));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_menu));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
} else {
if (editMode)
toolbar.setTitle(getAlbum().getSelectedCount() + "/" + getAlbum().getMedia().size());
else {
if (!all_photos)
toolbar.setTitle(getAlbum().getName());
else toolbar.setTitle(getString(R.string.all_media));
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayAlbums();
}
});
}
}
if (editMode) {
toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_check));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finishEditMode();
}
});
}
}
//called from onBackPressed()
private void finishEditMode() {
editMode = false;
if (albumsMode) {
getAlbums().clearSelectedAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
getAlbum().clearSelectedPhotos();
mediaAdapter.notifyDataSetChanged();
}
invalidateOptionsMenu();
}
private void checkNothing() {
TextView a = (TextView) findViewById(R.id.nothing_to_show);
a.setTextColor(getTextColor());
a.setVisibility((albumsMode && getAlbums().dispAlbums.size() == 0) || (!albumsMode && getAlbum().getMedia().size() == 0) ? View.VISIBLE : View.GONE);
}
//region MENU
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_albums, menu);
if (albumsMode) {
Drawable shareIcon = getResources().getDrawable(R.drawable.ic_photo_24dp, getTheme());
shareIcon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
menu.findItem(R.id.all_photos).setIcon(shareIcon);
menu.findItem(R.id.select_all).setTitle(
getString(getAlbums().getSelectedCount() == albumsAdapter.getItemCount()
? R.string.clear_selected
: R.string.select_all));
menu.findItem(R.id.ascending_sort_action).setChecked(getAlbums().getSortingOrder() == SortingOrder.ASCENDING);
switch (getAlbums().getSortingMode()) {
case NAME:
menu.findItem(R.id.name_sort_action).setChecked(true);
break;
case SIZE:
menu.findItem(R.id.size_sort_action).setChecked(true);
break;
case DATE:
default:
menu.findItem(R.id.date_taken_sort_action).setChecked(true);
break;
case NUMERIC:
menu.findItem(R.id.numeric_sort_action).setChecked(true);
break;
}
} else {
menu.findItem(R.id.select_all).setTitle(getString(
getAlbum().getSelectedCount() == mediaAdapter.getItemCount()
? R.string.clear_selected
: R.string.select_all));
menu.findItem(R.id.ascending_sort_action).setChecked(getAlbum().settings.getSortingOrder() == SortingOrder.ASCENDING);
switch (getAlbum().settings.getSortingMode()) {
case NAME:
menu.findItem(R.id.name_sort_action).setChecked(true);
break;
case SIZE:
menu.findItem(R.id.size_sort_action).setChecked(true);
break;
case TYPE:
menu.findItem(R.id.type_sort_action).setChecked(true);
break;
case DATE:
default:
menu.findItem(R.id.date_taken_sort_action).setChecked(true);
break;
case NUMERIC:
menu.findItem(R.id.numeric_sort_action).setChecked(true);
break;
}
}
menu.findItem(R.id.hideAlbumButton).setTitle(hidden ? getString(R.string.unhide) : getString(R.string.hide));
menu.findItem(R.id.delete_action).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_delete));
menu.findItem(R.id.sort_action).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_sort));
menu.findItem(R.id.sharePhotos).setIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_share));
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
if (albumsMode) {
editMode = getAlbums().getSelectedCount() != 0;
menu.setGroupVisible(R.id.album_options_menu, editMode);
menu.setGroupVisible(R.id.photos_option_men, false);
menu.findItem(R.id.all_photos).setVisible(true);
} else {
editMode = getAlbum().areMediaSelected();
menu.setGroupVisible(R.id.photos_option_men, editMode);
menu.setGroupVisible(R.id.album_options_menu, !editMode);
menu.findItem(R.id.all_photos).setVisible(false);
}
togglePrimaryToolbarOptions(menu);
updateSelectedStuff();
menu.findItem(R.id.excludeAlbumButton).setVisible(editMode);
menu.findItem(R.id.select_all).setVisible(editMode);
menu.findItem(R.id.type_sort_action).setVisible(!albumsMode);
menu.findItem(R.id.delete_action).setVisible(!albumsMode || editMode);
menu.findItem(R.id.clear_album_preview).setVisible(!albumsMode && getAlbum().hasCustomCover());
menu.findItem(R.id.renameAlbum).setVisible((albumsMode && getAlbums().getSelectedCount() == 1) || (!albumsMode && !editMode));
if (getAlbums().getSelectedCount() == 1)
menu.findItem(R.id.set_pin_album).setTitle(getAlbums().getSelectedAlbum(0).isPinned() ? getString(R.string.un_pin) : getString(R.string.pin));
menu.findItem(R.id.set_pin_album).setVisible(albumsMode && getAlbums().getSelectedCount() == 1);
menu.findItem(R.id.setAsAlbumPreview).setVisible(!albumsMode);
menu.findItem(R.id.affixPhoto).setVisible(!albumsMode && getAlbum().getSelectedCount() > 1);
return super.onPrepareOptionsMenu(menu);
}
private void togglePrimaryToolbarOptions(final Menu menu) {
menu.setGroupVisible(R.id.general_action, !editMode);
}
//endregion
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.all_photos:
if (!all_photos) {
all_photos = true;
displayAllMedia(true);
} else {
displayAlbums();
}
return true;
case R.id.select_all:
if (albumsMode) {
//if all albums are already selected, unselect all of them
if (getAlbums().getSelectedCount() == albumsAdapter.getItemCount()) {
editMode = false;
getAlbums().clearSelectedAlbums();
}
// else, select all albums
else getAlbums().selectAllAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
//if all photos are already selected, unselect all of them
if (getAlbum().getSelectedCount() == mediaAdapter.getItemCount()) {
editMode = false;
getAlbum().clearSelectedPhotos();
}
// else, select all photos
else getAlbum().selectAllPhotos();
mediaAdapter.notifyDataSetChanged();
}
invalidateOptionsMenu();
return true;
case R.id.set_pin_album:
getAlbums().getSelectedAlbum(0).settings.togglePin(getApplicationContext());
getAlbums().sortAlbums(getApplicationContext());
getAlbums().clearSelectedAlbums();
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
invalidateOptionsMenu();
return true;
case R.id.settings:
startActivity(new Intent(LFMainActivity.this, SettingsActivity.class));
return true;
case R.id.hideAlbumButton:
final AlertDialog.Builder hideDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(LFMainActivity.this, hideDialogBuilder,
hidden ? R.string.unhide : R.string.hide,
hidden ? R.string.unhide_album_message : R.string.hide_album_message);
hideDialogBuilder.setPositiveButton(getString(hidden ? R.string.unhide : R.string.hide).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (albumsMode) {
if (hidden) getAlbums().unHideSelectedAlbums(getApplicationContext());
else getAlbums().hideSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
if (hidden)
getAlbums().unHideAlbum(getAlbum().getPath(), getApplicationContext());
else
getAlbums().hideAlbum(getAlbum().getPath(), getApplicationContext());
displayAlbums(true);
}
}
});
if (!hidden) {
hideDialogBuilder.setNeutralButton(this.getString(R.string.exclude).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (albumsMode) {
getAlbums().excludeSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
customAlbumsHelper.excludeAlbum(getAlbum().getPath());
displayAlbums(true);
}
}
});
}
hideDialogBuilder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
hideDialogBuilder.show();
return true;
case R.id.delete_action:
class DeletePhotos extends AsyncTask<String, Integer, Boolean> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
//if in album mode, delete selected albums
if (albumsMode)
return getAlbums().deleteSelectedAlbums(LFMainActivity.this);
else {
// if in selection mode, delete selected media
if (editMode)
return getAlbum().deleteSelectedMedia(getApplicationContext());
// if not in selection mode, delete current album entirely
else {
boolean succ = getAlbums().deleteAlbum(getAlbum(), getApplicationContext());
getAlbum().getMedia().clear();
return succ;
}
}
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
// in albumsMode, the selected albums have been deleted.
if (albumsMode) {
getAlbums().clearSelectedAlbums();
albumsAdapter.notifyDataSetChanged();
} else {
//if all media in current album have been deleted, delete current album too.
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
} else
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
} else requestSdCardPermissions();
invalidateOptionsMenu();
checkNothing();
swipeRefreshLayout.setRefreshing(false);
}
}
AlertDialog.Builder deleteDialog = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
AlertDialogsHelper.getTextDialog(this, deleteDialog, R.string.delete, albumsMode || !editMode ? R.string.delete_album_message : R.string.delete_photos_message);
deleteDialog.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
deleteDialog.setPositiveButton(this.getString(R.string.delete).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (securityObj.isActiveSecurity() && securityObj.isPasswordOnDelete()) {
AlertDialog.Builder passwordDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextPassword = securityObj.getInsertPasswordDialog(LFMainActivity.this, passwordDialogBuilder);
passwordDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
passwordDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should br empty it will be overwrite later
//to avoid dismiss of the dialog on wrong password
}
});
final AlertDialog passwordDialog = passwordDialogBuilder.create();
passwordDialog.show();
passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if password is correct, call DeletePhotos and perform deletion
if (securityObj.checkPassword(editTextPassword.getText().toString())) {
passwordDialog.dismiss();
new DeletePhotos().execute();
}
// if password is incorrect, don't delete and notify user of incorrect password
else {
Toast.makeText(getApplicationContext(), R.string.wrong_password, Toast.LENGTH_SHORT).show();
editTextPassword.getText().clear();
editTextPassword.requestFocus();
}
}
});
} else new DeletePhotos().execute();
}
});
deleteDialog.show();
return true;
case R.id.excludeAlbumButton:
final AlertDialog.Builder excludeDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final View excludeDialogLayout = getLayoutInflater().inflate(R.layout.dialog_exclude, null);
TextView textViewExcludeTitle = (TextView) excludeDialogLayout.findViewById(R.id.text_dialog_title);
TextView textViewExcludeMessage = (TextView) excludeDialogLayout.findViewById(R.id.text_dialog_message);
final Spinner spinnerParents = (Spinner) excludeDialogLayout.findViewById(R.id.parents_folder);
spinnerParents.getBackground().setColorFilter(getIconColor(), PorterDuff.Mode.SRC_ATOP);
((CardView) excludeDialogLayout.findViewById(R.id.message_card)).setCardBackgroundColor(getCardBackgroundColor());
textViewExcludeTitle.setBackgroundColor(getPrimaryColor());
textViewExcludeTitle.setText(getString(R.string.exclude));
if ((albumsMode && getAlbums().getSelectedCount() > 1)) {
textViewExcludeMessage.setText(R.string.exclude_albums_message);
spinnerParents.setVisibility(View.GONE);
} else {
textViewExcludeMessage.setText(R.string.exclude_album_message);
spinnerParents.setAdapter(getSpinnerAdapter(albumsMode ? getAlbums().getSelectedAlbum(0).getParentsFolders() : getAlbum().getParentsFolders()));
}
textViewExcludeMessage.setTextColor(getTextColor());
excludeDialogBuilder.setView(excludeDialogLayout);
excludeDialogBuilder.setPositiveButton(this.getString(R.string.exclude).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if ((albumsMode && getAlbums().getSelectedCount() > 1)) {
getAlbums().excludeSelectedAlbums(getApplicationContext());
albumsAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
} else {
customAlbumsHelper.excludeAlbum(spinnerParents.getSelectedItem().toString());
finishEditMode();
displayAlbums(true);
}
}
});
excludeDialogBuilder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
excludeDialogBuilder.show();
return true;
case R.id.sharePhotos:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.sent_to_action));
// list of all selected media in current album
ArrayList<Uri> files = new ArrayList<Uri>();
for (Media f : getAlbum().getSelectedMedia())
files.add(f.getUri());
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
intent.setType(StringUtils.getGenericMIME(getAlbum().getSelectedMedia(0).getMimeType()));
finishEditMode();
startActivity(Intent.createChooser(intent, getResources().getText(R.string.send_to)));
return true;
case R.id.name_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(NAME);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), NAME);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.date_taken_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(DATE);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), DATE);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.size_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(SIZE);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), SIZE);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.type_sort_action:
if (!albumsMode) {
getAlbum().setDefaultSortingMode(getApplicationContext(), TYPE);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
item.setChecked(true);
}
return true;
case R.id.numeric_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingMode(NUMERIC);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingMode(getApplicationContext(), NUMERIC);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(true);
return true;
case R.id.ascending_sort_action:
if (albumsMode) {
getAlbums().setDefaultSortingAscending(item.isChecked() ? SortingOrder.DESCENDING : SortingOrder.ASCENDING);
getAlbums().sortAlbums(getApplicationContext());
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
} else {
getAlbum().setDefaultSortingAscending(getApplicationContext(), item.isChecked() ? SortingOrder.DESCENDING : SortingOrder.ASCENDING);
getAlbum().sortPhotos();
mediaAdapter.swapDataSet(getAlbum().getMedia());
}
item.setChecked(!item.isChecked());
return true;
//region Affix
case R.id.affixPhoto:
//region Async MediaAffix
class affixMedia extends AsyncTask<Affix.Options, Integer, Void> {
private AlertDialog dialog;
@Override
protected void onPreExecute() {
AlertDialog.Builder progressDialog = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
dialog = AlertDialogsHelper.getProgressDialog(LFMainActivity.this, progressDialog,
getString(R.string.affix), getString(R.string.affix_text));
dialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Affix.Options... arg0) {
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
for (int i = 0; i < getAlbum().getSelectedCount(); i++) {
if (!getAlbum().getSelectedMedia(i).isVideo())
bitmapArray.add(getBitmap(getAlbum().getSelectedMedia(i).getPath()));
}
if (bitmapArray.size() > 1)
Affix.AffixBitmapList(getApplicationContext(), bitmapArray, arg0[0]);
else runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), R.string.affix_error, Toast.LENGTH_SHORT).show();
}
});
return null;
}
@Override
protected void onPostExecute(Void result) {
editMode = false;
getAlbum().clearSelectedPhotos();
dialog.dismiss();
invalidateOptionsMenu();
mediaAdapter.notifyDataSetChanged();
new PreparePhotosTask().execute();
}
}
//endregion
final AlertDialog.Builder builder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final View dialogLayout = getLayoutInflater().inflate(R.layout.dialog_affix, null);
dialogLayout.findViewById(R.id.affix_title).setBackgroundColor(getPrimaryColor());
((CardView) dialogLayout.findViewById(R.id.affix_card)).setCardBackgroundColor(getCardBackgroundColor());
//ITEMS
final SwitchCompat swVertical = (SwitchCompat) dialogLayout.findViewById(R.id.affix_vertical_switch);
final SwitchCompat swSaveHere = (SwitchCompat) dialogLayout.findViewById(R.id.save_here_switch);
final RadioGroup radioFormatGroup = (RadioGroup) dialogLayout.findViewById(R.id.radio_format);
final TextView txtQuality = (TextView) dialogLayout.findViewById(R.id.affix_quality_title);
final SeekBar seekQuality = (SeekBar) dialogLayout.findViewById(R.id.seek_bar_quality);
//region THEME STUFF
setScrollViewColor((ScrollView) dialogLayout.findViewById(R.id.affix_scrollView));
/** TextViews **/
int color = getTextColor();
((TextView) dialogLayout.findViewById(R.id.affix_vertical_title)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.compression_settings_title)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.save_here_title)).setTextColor(color);
/** Sub TextViews **/
color = getTextColor();
((TextView) dialogLayout.findViewById(R.id.save_here_sub)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.affix_vertical_sub)).setTextColor(color);
((TextView) dialogLayout.findViewById(R.id.affix_format_sub)).setTextColor(color);
txtQuality.setTextColor(color);
/** Icons **/
color = getIconColor();
((IconicsImageView) dialogLayout.findViewById(R.id.affix_quality_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.affix_format_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.affix_vertical_icon)).setColor(color);
((IconicsImageView) dialogLayout.findViewById(R.id.save_here_icon)).setColor(color);
seekQuality.getProgressDrawable().setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));
seekQuality.getThumb().setColorFilter(new PorterDuffColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_jpeg));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_png));
updateRadioButtonColor((RadioButton) dialogLayout.findViewById(R.id.radio_webp));
updateSwitchColor(swVertical, getAccentColor());
updateSwitchColor(swSaveHere, getAccentColor());
//endregion
seekQuality.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
txtQuality.setText(Html.fromHtml(
String.format(Locale.getDefault(), "%s <b>%d</b>", getString(R.string.quality), progress)));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekQuality.setProgress(90); //DEFAULT
swVertical.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateSwitchColor(swVertical, getAccentColor());
}
});
swSaveHere.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateSwitchColor(swSaveHere, getAccentColor());
}
});
builder.setView(dialogLayout);
builder.setPositiveButton(this.getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Bitmap.CompressFormat compressFormat;
switch (radioFormatGroup.getCheckedRadioButtonId()) {
case R.id.radio_jpeg:
default:
compressFormat = Bitmap.CompressFormat.JPEG;
break;
case R.id.radio_png:
compressFormat = Bitmap.CompressFormat.PNG;
break;
case R.id.radio_webp:
compressFormat = Bitmap.CompressFormat.WEBP;
break;
}
Affix.Options options = new Affix.Options(
swSaveHere.isChecked() ? getAlbum().getPath() : Affix.getDefaultDirectoryPath(),
compressFormat,
seekQuality.getProgress(),
swVertical.isChecked());
new affixMedia().execute(options);
}
});
builder.setNegativeButton(this.getString(R.string.cancel).toUpperCase(), null);
builder.show();
return true;
//endregion
case R.id.action_move:
bottomSheetDialogFragment = new SelectAlbumBottomSheet();
bottomSheetDialogFragment.setTitle(getString(R.string.move_to));
bottomSheetDialogFragment.setSelectAlbumInterface(new SelectAlbumBottomSheet.SelectAlbumInterface() {
@Override
public void folderSelected(String path) {
swipeRefreshLayout.setRefreshing(true);
if (getAlbum().moveSelectedMedia(getApplicationContext(), path) > 0) {
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
}
mediaAdapter.swapDataSet(getAlbum().getMedia());
finishEditMode();
invalidateOptionsMenu();
} else requestSdCardPermissions();
swipeRefreshLayout.setRefreshing(false);
bottomSheetDialogFragment.dismiss();
}
});
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
return true;
case R.id.action_copy:
bottomSheetDialogFragment = new SelectAlbumBottomSheet();
bottomSheetDialogFragment.setTitle(getString(R.string.copy_to));
bottomSheetDialogFragment.setSelectAlbumInterface(new SelectAlbumBottomSheet.SelectAlbumInterface() {
@Override
public void folderSelected(String path) {
boolean success = getAlbum().copySelectedPhotos(getApplicationContext(), path);
finishEditMode();
bottomSheetDialogFragment.dismiss();
if (!success)
requestSdCardPermissions();
}
});
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
return true;
case R.id.renameAlbum:
AlertDialog.Builder renameDialogBuilder = new AlertDialog.Builder(LFMainActivity.this, getDialogStyle());
final EditText editTextNewName = new EditText(getApplicationContext());
editTextNewName.setText(albumsMode ? getAlbums().getSelectedAlbum(0).getName() : getAlbum().getName());
AlertDialogsHelper.getInsertTextDialog(LFMainActivity.this, renameDialogBuilder,
editTextNewName, R.string.rename_album);
renameDialogBuilder.setNegativeButton(getString(R.string.cancel).toUpperCase(), null);
renameDialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//This should br empty it will be overwrite later
//to avoid dismiss of the dialog
}
});
final AlertDialog renameDialog = renameDialogBuilder.create();
renameDialog.show();
renameDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View dialog) {
if (editTextNewName.length() != 0) {
swipeRefreshLayout.setRefreshing(true);
boolean success = false;
if (albumsMode) {
int index = getAlbums().dispAlbums.indexOf(getAlbums().getSelectedAlbum(0));
getAlbums().getAlbum(index).updatePhotos(getApplicationContext());
success = getAlbums().getAlbum(index).renameAlbum(getApplicationContext(),
editTextNewName.getText().toString());
albumsAdapter.notifyItemChanged(index);
} else {
success = getAlbum().renameAlbum(getApplicationContext(), editTextNewName.getText().toString());
toolbar.setTitle(getAlbum().getName());
mediaAdapter.notifyDataSetChanged();
}
renameDialog.dismiss();
if (success){
Snackbar.make(getWindow().getDecorView().getRootView(),
getString(R.string.rename_succes),Snackbar.LENGTH_LONG).show();
}else {
Snackbar.make(getWindow().getDecorView().getRootView(),
getString(R.string.rename_error),Snackbar.LENGTH_LONG)
.show();
requestSdCardPermissions();
}
swipeRefreshLayout.setRefreshing(false);
} else {
StringUtils.showToast(getApplicationContext(), getString(R.string.insert_something));
editTextNewName.requestFocus();
}
}
});
return true;
case R.id.clear_album_preview:
if (!albumsMode) {
getAlbum().removeCoverAlbum(getApplicationContext());
}
return true;
case R.id.setAsAlbumPreview:
if (!albumsMode) {
getAlbum().setSelectedPhotoAsPreview(getApplicationContext());
finishEditMode();
}
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap bitmap = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = bitmap.getHeight();
int width = bitmap.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) x,
(int) y, true);
bitmap.recycle();
bitmap = scaledBitmap;
System.gc();
} else {
bitmap = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " +bitmap.getWidth() + ", height: " +
bitmap.getHeight());
return bitmap;
} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;
}
}
/**
* If we are in albumsMode, make the albums recyclerView visible. If we are not, make media recyclerView visible.
* @param albumsMode it indicates whether we are in album selection mode or not
*/
private void toggleRecyclersVisibility(boolean albumsMode) {
rvAlbums.setVisibility(albumsMode ? View.VISIBLE : View.GONE);
rvMedia.setVisibility(albumsMode ? View.GONE : View.VISIBLE);
//touchScrollBar.setScrollBarHidden(albumsMode);
}
/**
* handles back presses.
* If we are currently in selection mode, back press will take us out of selection mode.
* If we are not in selection mode but in albumsMode and the drawer is open, back press will close it.
* If we are not in selection mode but in albumsMode and the drawer is closed, finish the activity.
* If we are neither in selection mode nor in albumsMode, display the albums again.
*/
@Override
public void onBackPressed() {
if (editMode) finishEditMode();
else {
if (albumsMode) {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
mDrawerLayout.closeDrawer(GravityCompat.START);
else finish();
} else {
displayAlbums();
setRecentApp(getString(R.string.app_name));
}
}
}
private class PrepareAlbumTask extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
toggleRecyclersVisibility(true);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
getAlbums().loadAlbums(getApplicationContext(), hidden);
return null;
}
@Override
protected void onPostExecute(Void result) {
albumsAdapter.swapDataSet(getAlbums().dispAlbums);
checkNothing();
swipeRefreshLayout.setRefreshing(false);
getAlbums().saveBackup(getApplicationContext());
invalidateOptionsMenu();
finishEditMode();
}
}
private class PreparePhotosTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
toggleRecyclersVisibility(false);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
getAlbum().updatePhotos(getApplicationContext());
return null;
}
@Override
protected void onPostExecute(Void result) {
mediaAdapter.swapDataSet(getAlbum().getMedia());
if (!hidden)
HandlingAlbums.addAlbumToBackup(getApplicationContext(), getAlbum());
checkNothing();
swipeRefreshLayout.setRefreshing(false);
invalidateOptionsMenu();
finishEditMode();
}
}
private class PrepareAllPhotos extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
toggleRecyclersVisibility(false);
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
getAlbum().updatePhotos(getApplicationContext());
return null;
}
@Override
protected void onPostExecute(Void result) {
mediaAdapter.swapDataSet(StorageProvider.getAllShownImages(LFMainActivity.this));
if (!hidden)
HandlingAlbums.addAlbumToBackup(getApplicationContext(), getAlbum());
checkNothing();
swipeRefreshLayout.setRefreshing(false);
invalidateOptionsMenu();
finishEditMode();
toolbar.setTitle(getString(R.string.all_media));
clearSelectedPhotos();
}
}
/*private class MovePhotos extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
boolean success = true;
try
{
for (int i = 0; i < getAlbum().selectedMedias.size(); i++) {
File from = new File(getAlbum().selectedMedias.get(i).getPath());
File to = new File(StringUtils.getPhotoPathMoved(getAlbum().selectedMedias.get(i).getPath(), arg0[0]));
if (ContentHelper.moveFile(getApplicationContext(), from, to)) {
MediaScannerConnection.scanFile(getApplicationContext(),
new String[]{ to.getAbsolutePath(), from.getAbsolutePath() }, null, null);
getAlbum().getMedia().remove(getAlbum().selectedMedias.get(i));
} else success = false;
}
} catch (Exception e) { e.printStackTrace(); }
return success;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
if (getAlbum().getMedia().size() == 0) {
getAlbums().removeCurrentAlbum();
albumsAdapter.notifyDataSetChanged();
displayAlbums();
}
} else requestSdCardPermissions();
mediaAdapter.swapDataSet(getAlbum().getMedia());
finishEditMode();
invalidateOptionsMenu();
swipeRefreshLayout.setRefreshing(false);
}
}*/
}
|
Added long click options to all photos list (#673)
|
app/src/main/java/org/fossasia/phimpme/leafpic/activities/LFMainActivity.java
|
Added long click options to all photos list (#673)
|
<ide><path>pp/src/main/java/org/fossasia/phimpme/leafpic/activities/LFMainActivity.java
<ide> package org.fossasia.phimpme.leafpic.activities;
<ide>
<ide> import android.annotation.TargetApi;
<add>import android.content.ContentResolver;
<add>import android.content.ContentUris;
<ide> import android.content.DialogInterface;
<ide> import android.content.Intent;
<ide> import android.content.res.Configuration;
<add>import android.database.Cursor;
<ide> import android.graphics.Bitmap;
<ide> import android.graphics.BitmapFactory;
<ide> import android.graphics.Color;
<ide> import android.os.AsyncTask;
<ide> import android.os.Build;
<ide> import android.os.Bundle;
<add>import android.provider.MediaStore;
<ide> import android.support.design.widget.Snackbar;
<ide> import android.support.v4.content.ContextCompat;
<ide> import android.support.v4.view.GravityCompat;
<ide> import android.view.Menu;
<ide> import android.view.MenuItem;
<ide> import android.view.View;
<add>import android.webkit.MimeTypeMap;
<ide> import android.widget.CompoundButton;
<ide> import android.widget.EditText;
<ide> import android.widget.RadioButton;
<ide> }
<ide> else
<ide> toolbar.setTitle(selectedMedias.size() + "/" + size);
<add> invalidateOptionsMenu();
<ide> return index;
<ide> }
<ide>
<ide> if (selectedMedias!=null)
<ide> selectedMedias.clear();
<ide> toolbar.setTitle(getString(R.string.all));
<add> }
<add>
<add> public void selectAllPhotos(){
<add> for (Media m : media) {
<add> m.setSelected(true);
<add> selectedMedias.add(m);
<add> }
<add> toolbar.setTitle(selectedMedias.size() + "/" + size);
<ide> }
<ide>
<ide>
<ide> }
<ide> } else {
<ide> if (editMode)
<add> if (!all_photos)
<ide> toolbar.setTitle(getAlbum().getSelectedCount() + "/" + getAlbum().getMedia().size());
<add> else toolbar.setTitle(selectedMedias.size() + "/" + size);
<ide> else {
<ide> if (!all_photos)
<ide> toolbar.setTitle(getAlbum().getName());
<ide> @Override
<ide> public void onClick(View v) {
<ide> finishEditMode();
<add> clearSelectedPhotos();
<ide> }
<ide> });
<ide> }
<ide> } else {
<ide> menu.findItem(R.id.select_all).setTitle(getString(
<ide> getAlbum().getSelectedCount() == mediaAdapter.getItemCount()
<add> || selectedMedias.size() == size
<ide> ? R.string.clear_selected
<ide> : R.string.select_all));
<ide> menu.findItem(R.id.ascending_sort_action).setChecked(getAlbum().settings.getSortingOrder() == SortingOrder.ASCENDING);
<ide> menu.setGroupVisible(R.id.photos_option_men, false);
<ide> menu.findItem(R.id.all_photos).setVisible(true);
<ide> } else {
<del> editMode = getAlbum().areMediaSelected();
<del> menu.setGroupVisible(R.id.photos_option_men, editMode);
<del> menu.setGroupVisible(R.id.album_options_menu, !editMode);
<del> menu.findItem(R.id.all_photos).setVisible(false);
<add> if (!all_photos) {
<add> editMode = getAlbum().areMediaSelected();
<add> menu.setGroupVisible(R.id.photos_option_men, editMode);
<add> menu.setGroupVisible(R.id.album_options_menu, !editMode);
<add> menu.findItem(R.id.all_photos).setVisible(false);
<add> } else {
<add> editMode = selectedMedias.size() != 0 ? true : false;
<add> menu.setGroupVisible(R.id.photos_option_men, editMode);
<add> menu.setGroupVisible(R.id.album_options_menu, !editMode);
<add> menu.findItem(R.id.all_photos).setVisible(false);
<add> }
<ide> }
<ide>
<ide> togglePrimaryToolbarOptions(menu);
<ide> updateSelectedStuff();
<ide>
<del> menu.findItem(R.id.excludeAlbumButton).setVisible(editMode);
<add> menu.findItem(R.id.action_copy).setVisible(!all_photos);
<add> menu.findItem(R.id.action_move).setVisible(!all_photos);
<add> menu.findItem(R.id.excludeAlbumButton).setVisible(editMode && !all_photos);
<ide> menu.findItem(R.id.select_all).setVisible(editMode);
<ide> menu.findItem(R.id.type_sort_action).setVisible(!albumsMode);
<del> menu.findItem(R.id.delete_action).setVisible(!albumsMode || editMode);
<add> menu.findItem(R.id.delete_action).setVisible((!albumsMode || editMode));
<add> menu.findItem(R.id.hideAlbumButton).setVisible(!all_photos);
<ide>
<ide> menu.findItem(R.id.clear_album_preview).setVisible(!albumsMode && getAlbum().hasCustomCover());
<del> menu.findItem(R.id.renameAlbum).setVisible((albumsMode && getAlbums().getSelectedCount() == 1) || (!albumsMode && !editMode));
<add> menu.findItem(R.id.renameAlbum).setVisible(((albumsMode && getAlbums().getSelectedCount() == 1) || (!albumsMode && !editMode)) && !all_photos);
<ide> if (getAlbums().getSelectedCount() == 1)
<ide> menu.findItem(R.id.set_pin_album).setTitle(getAlbums().getSelectedAlbum(0).isPinned() ? getString(R.string.un_pin) : getString(R.string.pin));
<ide> menu.findItem(R.id.set_pin_album).setVisible(albumsMode && getAlbums().getSelectedCount() == 1);
<del> menu.findItem(R.id.setAsAlbumPreview).setVisible(!albumsMode);
<del> menu.findItem(R.id.affixPhoto).setVisible(!albumsMode && getAlbum().getSelectedCount() > 1);
<add> menu.findItem(R.id.setAsAlbumPreview).setVisible(!albumsMode && !all_photos);
<add> menu.findItem(R.id.affixPhoto).setVisible(!albumsMode && (getAlbum().getSelectedCount() > 1) || selectedMedias.size() > 1);
<ide> return super.onPrepareOptionsMenu(menu);
<ide> }
<ide>
<ide> else getAlbums().selectAllAlbums();
<ide> albumsAdapter.notifyDataSetChanged();
<ide> } else {
<del> //if all photos are already selected, unselect all of them
<del> if (getAlbum().getSelectedCount() == mediaAdapter.getItemCount()) {
<del> editMode = false;
<del> getAlbum().clearSelectedPhotos();
<del> }
<del> // else, select all photos
<del> else getAlbum().selectAllPhotos();
<del> mediaAdapter.notifyDataSetChanged();
<add> if (!all_photos) {
<add> //if all photos are already selected, unselect all of them
<add> if (getAlbum().getSelectedCount() == mediaAdapter.getItemCount()) {
<add> editMode = false;
<add> getAlbum().clearSelectedPhotos();
<add> }
<add> // else, select all photos
<add> else getAlbum().selectAllPhotos();
<add> mediaAdapter.notifyDataSetChanged();
<add> } else {
<add>
<add> if (selectedMedias.size() == size) {
<add> editMode = false;
<add> clearSelectedPhotos();
<add> }
<add> // else, select all photos
<add> else {
<add> clearSelectedPhotos();
<add> selectAllPhotos();
<add> }
<add> mediaAdapter.notifyDataSetChanged();
<add> }
<ide> }
<ide> invalidateOptionsMenu();
<ide> return true;
<ide> return getAlbums().deleteSelectedAlbums(LFMainActivity.this);
<ide> else {
<ide> // if in selection mode, delete selected media
<del> if (editMode)
<add> if (editMode && !all_photos)
<ide> return getAlbum().deleteSelectedMedia(getApplicationContext());
<add> else if (all_photos) {
<add> Boolean succ = false;
<add> for (Media media : selectedMedias) {
<add> String[] projection = {MediaStore.Images.Media._ID};
<add>
<add> // Match on the file path
<add> String selection = MediaStore.Images.Media.DATA + " = ?";
<add> String[] selectionArgs = new String[]{media.getPath()};
<add>
<add> // Query for the ID of the media matching the file path
<add> Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
<add> ContentResolver contentResolver = getContentResolver();
<add> Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
<add> if (c.moveToFirst()) {
<add> // We found the ID. Deleting the item via the content provider will also remove the file
<add> long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
<add> Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
<add> contentResolver.delete(deleteUri, null, null);
<add> succ = true;
<add> } else {
<add> succ = false;
<add> // File not found in media store DB
<add> }
<add> c.close();
<add> }
<add> return succ;
<add> }
<ide> // if not in selection mode, delete current album entirely
<ide> else {
<ide> boolean succ = getAlbums().deleteAlbum(getAlbum(), getApplicationContext());
<ide> getAlbums().clearSelectedAlbums();
<ide> albumsAdapter.notifyDataSetChanged();
<ide> } else {
<del> //if all media in current album have been deleted, delete current album too.
<del> if (getAlbum().getMedia().size() == 0) {
<del> getAlbums().removeCurrentAlbum();
<del> albumsAdapter.notifyDataSetChanged();
<del> displayAlbums();
<del> } else
<del> mediaAdapter.swapDataSet(getAlbum().getMedia());
<add> if (!all_photos) {
<add> //if all media in current album have been deleted, delete current album too.
<add> if (getAlbum().getMedia().size() == 0) {
<add> getAlbums().removeCurrentAlbum();
<add> albumsAdapter.notifyDataSetChanged();
<add> displayAlbums();
<add> } else
<add> mediaAdapter.swapDataSet(getAlbum().getMedia());
<add> } else {
<add> clearSelectedPhotos();
<add> listAll = StorageProvider.getAllShownImages(LFMainActivity.this);
<add> media = listAll;
<add> size = listAll.size();
<add> mediaAdapter.swapDataSet(listAll);
<add> }
<ide> }
<ide> } else requestSdCardPermissions();
<ide>
<ide>
<ide> // list of all selected media in current album
<ide> ArrayList<Uri> files = new ArrayList<Uri>();
<del> for (Media f : getAlbum().getSelectedMedia())
<del> files.add(f.getUri());
<add> if (!all_photos) {
<add> for (Media f : getAlbum().getSelectedMedia())
<add> files.add(f.getUri());
<add> } else {
<add> for (Media f : selectedMedias)
<add> files.add(f.getUri());
<add> }
<add> String extension = files.get(0).getPath().substring(files.get(0).getPath().lastIndexOf('.') + 1);
<add> String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
<ide>
<ide> intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
<add> if (!all_photos)
<ide> intent.setType(StringUtils.getGenericMIME(getAlbum().getSelectedMedia(0).getMimeType()));
<add> else intent.setType(mimeType);
<ide> finishEditMode();
<ide> startActivity(Intent.createChooser(intent, getResources().getText(R.string.send_to)));
<ide> return true;
<ide> @Override
<ide> protected Void doInBackground(Affix.Options... arg0) {
<ide> ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
<del> for (int i = 0; i < getAlbum().getSelectedCount(); i++) {
<del> if (!getAlbum().getSelectedMedia(i).isVideo())
<add> if (!all_photos) {
<add> for (int i = 0; i < getAlbum().getSelectedCount(); i++) {
<ide> bitmapArray.add(getBitmap(getAlbum().getSelectedMedia(i).getPath()));
<add> }
<add> } else {
<add> for (int i = 0; i < selectedMedias.size(); i++) {
<add> bitmapArray.add(getBitmap(selectedMedias.get(i).getPath()));
<add> }
<ide> }
<ide>
<ide> if (bitmapArray.size() > 1)
<ide> @Override
<ide> protected void onPostExecute(Void result) {
<ide> editMode = false;
<add> if(!all_photos)
<ide> getAlbum().clearSelectedPhotos();
<add> else clearSelectedPhotos();
<ide> dialog.dismiss();
<ide> invalidateOptionsMenu();
<ide> mediaAdapter.notifyDataSetChanged();
<del> new PreparePhotosTask().execute();
<add> if(!all_photos)
<add> new PreparePhotosTask().execute();
<add> else clearSelectedPhotos();
<add>
<ide> }
<ide> }
<ide> //endregion
|
|
Java
|
apache-2.0
|
a9bdce498fcccead63a94f5875bd76131369152e
| 0 |
opennetworkinglab/onos-warden,opennetworkinglab/onos-warden,opennetworkinglab/onos-warden,opennetworkinglab/onos-warden,opennetworkinglab/onos-warden,opennetworkinglab/onos-warden
|
/*
* Copyright 2016 Open Networking 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 implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onlab.warden;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.*;
/**
* Warden for tracking use of shared test cells.
*/
class Warden {
private static final String CELL_NOT_NULL = "Cell name cannot be null";
private static final String USER_NOT_NULL = "User name cannot be null";
private static final String KEY_NOT_NULL = "User key cannot be null";
private static final String UTF_8 = "UTF-8";
private static final long TIMEOUT = 10; // 10 seconds
private static final int MAX_MINUTES = 1_440; // 24 hours max
private static final int MINUTE = 60_000; // 1 minute
private static final int DEFAULT_MINUTES = 120; // 2 hours
private static final String DEFAULT_SPEC = "3+1";
private static final String SSH_COMMAND = "ssh -o ConnectTimeout=5";
private final File log = new File("warden.log");
// Allow overriding these for unit tests.
static String cmdPrefix = "";
static File root = new File(".");
private final File cells = new File(root, "cells");
private final File supported = new File(cells, "supported");
private final File reserved = new File(cells, "reserved");
private final Random random = new Random();
/**
* Creates a new cell warden.
*/
Warden() {
if (reserved.mkdirs()) {
System.out.println("Created " + reserved + " directory");
}
random.setSeed(System.currentTimeMillis());
Timer timer = new Timer("cell-pruner", true);
timer.schedule(new Reposessor(), MINUTE / 4, MINUTE / 2);
}
/**
* Returns list of names of supported cells.
*
* @return list of cell names
*/
Set<String> getCells() {
String[] list = supported.list();
return list != null ? ImmutableSet.copyOf(list) : ImmutableSet.of();
}
/**
* Returns list of names of available cells.
*
* @return list of cell names
*/
Set<String> getAvailableCells() {
Set<String> available = new HashSet<>(getCells());
available.removeAll(getReservedCells());
return ImmutableSet.copyOf(available);
}
/**
* Returns list of names of reserved cells.
*
* @return list of cell names
*/
Set<String> getReservedCells() {
String[] list = reserved.list();
return list != null ? ImmutableSet.copyOf(list) : ImmutableSet.of();
}
/**
* Returns the host name on which the specified cell is hosted.
*
* @param cellName cell name
* @return host name where the cell runs
*/
String getCellHost(String cellName) {
return getCellInfo(cellName).hostName;
}
/**
* Returns reservation for the specified user.
*
* @param userName user name
* @return cell reservation record or null if user does not have one
*/
Reservation currentUserReservation(String userName) {
checkNotNull(userName, USER_NOT_NULL);
for (String cellName : getReservedCells()) {
Reservation reservation = currentCellReservation(cellName);
if (reservation != null && userName.equals(reservation.userName)) {
return reservation;
}
}
return null;
}
/**
* Returns the name of the user who reserved the given cell.
*
* @param cellName cell name
* @return cell reservation record or null if cell is not reserved
*/
Reservation currentCellReservation(String cellName) {
checkNotNull(cellName, CELL_NOT_NULL);
File cellFile = new File(reserved, cellName);
if (!cellFile.exists()) {
return null;
}
try (InputStream stream = new FileInputStream(cellFile)) {
return new Reservation(new String(ByteStreams.toByteArray(stream), "UTF-8"));
} catch (IOException e) {
throw new IllegalStateException("Unable to get current user for cell " + cellName, e);
}
}
/**
* Reserves a cell for the specified user and their public access key.
*
* @param userName user name
* @param sshKey user ssh public key
* @param minutes optional number of minutes for reservation
* @param cellSpec optional cell specification string
* @param cellNameHint optional cell name hint
* @return reserved cell definition
*/
synchronized String borrowCell(String userName, String sshKey, int minutes,
String cellSpec, String cellNameHint) {
checkNotNull(userName, USER_NOT_NULL);
checkArgument(userName.matches("[\\w.-]+"), "Invalid user name %s", userName);
checkNotNull(sshKey, KEY_NOT_NULL);
checkArgument(minutes <= MAX_MINUTES, "Number of minutes must be less than %d", MAX_MINUTES);
checkArgument(minutes >= 0, "Number of minutes must be non-negative");
checkArgument(cellSpec == null || cellSpec.matches("[\\d]\\+[0-1]"),
"Invalid cell spec string %s", cellSpec);
Reservation reservation = currentUserReservation(userName);
boolean alreadyReserved = reservation != null;
if (reservation == null) {
// If there is no reservation for the user, create one
String cellName = findAvailableCell(cellNameHint);
reservation = new Reservation(cellName, userName, System.currentTimeMillis(),
minutes == 0 ? DEFAULT_MINUTES : minutes,
cellSpec == null ? DEFAULT_SPEC : cellSpec);
} else if (minutes == 0) {
// If minutes are 0, simply return the cell definition
return getCellDefinition(reservation.cellName);
} else {
// If minutes are > 0, update the existing cell reservation
reservation = new Reservation(reservation.cellName, userName,
System.currentTimeMillis(), minutes,
reservation.cellSpec);
}
reserveCell(reservation);
if (!alreadyReserved) {
createCell(reservation, sshKey);
}
log(userName, reservation.cellName, reservation.cellSpec,
"borrowed for " + reservation.duration + " minutes");
return getCellDefinition(reservation.cellName);
}
/**
* Returns name of an available cell. Cell is chosen based on the load
* of its hosting server; a random one will be chosen from the set of
* cells hosted by the least loaded server.
*
* @param cellNameHint optional hint for requesting a specific cell
* @return name of an available cell
*/
private String findAvailableCell(String cellNameHint) {
Set<String> cells = getAvailableCells();
checkState(!cells.isEmpty(), "No cells are presently available");
Map<String, ServerInfo> load = Maps.newHashMap();
cells.stream().map(this::getCellInfo)
.forEach(info -> load.compute(info.hostName, (k, v) -> v == null ?
new ServerInfo(info.hostName, info) : v.bumpLoad(info)));
if (cellNameHint != null && !cellNameHint.isEmpty() && cells.contains(cellNameHint)) {
return cellNameHint;
}
List<ServerInfo> servers = new ArrayList<>(load.values());
servers.sort((a, b) -> b.load - a.load);
for (ServerInfo server : servers) {
if (isAvailable(server)) {
return server.cells.get(random.nextInt(server.cells.size())).cellName;
}
}
throw new IllegalStateException("Unable to find available cell");
}
/**
* Determines whether the specified cell server is available.
*
* @param server cell server address
* @return true if available, false otherwise
*/
private boolean isAvailable(ServerInfo server) {
String key = Integer.toString(random.nextInt());
String result = exec(String.format("%s %s echo %s", SSH_COMMAND, server.hostName, key));
return result != null && result.contains(key);
}
/**
* Returns the specified cell for the specified user and their public access key.
*
* @param userName user name
*/
synchronized void returnCell(String userName) {
checkNotNull(userName, USER_NOT_NULL);
Reservation reservation = currentUserReservation(userName);
checkState(reservation != null, "User %s has no cell reservations", userName);
unreserveCell(reservation);
destroyCell(reservation);
log(userName, reservation.cellName, reservation.cellSpec, "returned");
}
/**
* Powers on/off the specified machine.
*
* @param userName user name (used for verification)
* @param nodeIp IP of the node to shutdown
* @param on true if node is to be powered on; false to power off
* @return summary of the command success or error
*/
String powerControl(String userName, String nodeIp, boolean on) {
checkNotNull(userName, USER_NOT_NULL);
Reservation reservation = currentUserReservation(userName);
checkState(reservation != null, "User %s has no cell reservations", userName);
CellInfo cellInfo = getCellInfo(reservation.cellName);
log(userName, reservation.cellName, reservation.cellSpec,
nodeIp + " powered " + on ? "on" : "off");
return exec(String.format("%s %s warden/bin/power-node %s %s %s", SSH_COMMAND,
cellInfo.hostName, cellInfo.cellName, nodeIp, on ? "on" : "off"));
}
/**
* Reserves the specified cell for the user the source file and writes the
* specified content to the target file.
*
* @param reservation cell reservation record
*/
private void reserveCell(Reservation reservation) {
File cellFile = new File(reserved, reservation.cellName);
try (FileOutputStream stream = new FileOutputStream(cellFile)) {
stream.write(reservation.encode().getBytes(UTF_8));
} catch (IOException e) {
throw new IllegalStateException("Unable to reserve cell " + reservation.cellName, e);
}
}
/**
* Returns the cell definition of the specified cell.
*
* @param cellName cell name
* @return cell definition
*/
private String getCellDefinition(String cellName) {
CellInfo cellInfo = getCellInfo(cellName);
return exec(String.format("%s %s warden/bin/cell-def %s",
SSH_COMMAND, cellInfo.hostName, cellInfo.cellName));
}
/**
* Cancels the specified reservation.
*
* @param reservation reservation record
*/
private void unreserveCell(Reservation reservation) {
checkState(new File(reserved, reservation.cellName).delete(),
"Unable to return cell %s", reservation.cellName);
}
/**
* Creates the cell for the specified user SSH key.
*
* @param reservation cell reservation
* @param sshKey ssh key
*/
private void createCell(Reservation reservation, String sshKey) {
CellInfo cellInfo = getCellInfo(reservation.cellName);
String cmd = String.format("%s %s warden/bin/create-cell %s %s %s %s",
SSH_COMMAND, cellInfo.hostName, cellInfo.cellName,
cellInfo.ipPrefix, reservation.cellSpec, sshKey);
exec(cmd);
}
/**
* Destroys the specified cell.
*
* @param reservation reservation record
*/
private void destroyCell(Reservation reservation) {
CellInfo cellInfo = getCellInfo(reservation.cellName);
exec(String.format("%s %s warden/bin/destroy-cell %s %s", SSH_COMMAND,
cellInfo.hostName, cellInfo.cellName, reservation.cellSpec));
}
/**
* Reads the information about the specified cell.
*
* @param cellName cell name
* @return cell information
*/
private CellInfo getCellInfo(String cellName) {
File cellFile = new File(supported, cellName);
try (InputStream stream = new FileInputStream(cellFile)) {
String[] fields = new String(ByteStreams.toByteArray(stream), UTF_8).split(" ");
return new CellInfo(cellName, fields[0], fields[1]);
} catch (IOException e) {
throw new IllegalStateException("Unable to definition for cell " + cellName, e);
}
}
// Executes the specified command.
private String exec(String command) {
try {
Process process = Runtime.getRuntime().exec(cmdPrefix + command);
String output = new String(ByteStreams.toByteArray(process.getInputStream()), UTF_8);
process.waitFor(TIMEOUT, TimeUnit.SECONDS);
return process.exitValue() == 0 ? output : null;
} catch (Exception e) {
throw new IllegalStateException("Unable to execute " + command);
}
}
// Creates an audit log entry.
private void log(String userName, String cellName, String cellSpec, String action) {
try (FileOutputStream fos = new FileOutputStream(log, true);
PrintWriter pw = new PrintWriter(fos)) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
pw.println(String.format("%s\t%s\t%s-%s\t%s", format.format(new Date()),
userName, cellName, cellSpec, action));
pw.flush();
} catch (IOException e) {
throw new IllegalStateException("Unable to log reservation action", e);
}
}
// Carrier of cell information
private final class CellInfo {
final String cellName;
final String hostName;
final String ipPrefix;
private CellInfo(String cellName, String hostName, String ipPrefix) {
this.cellName = cellName;
this.hostName = hostName;
this.ipPrefix = ipPrefix;
}
}
// Carrier of cell server information
private final class ServerInfo {
final String hostName;
boolean isAvailable = false;
int load = 0;
List<CellInfo> cells = Lists.newArrayList();
private ServerInfo(String hostName, CellInfo info) {
this.hostName = hostName;
bumpLoad(info);
}
private ServerInfo bumpLoad(CellInfo info) {
cells.add(info);
load++; // TODO: bump by cell size later
return this;
}
}
// Task for re-possessing overdue cells
private final class Reposessor extends TimerTask {
@Override
public void run() {
long now = System.currentTimeMillis();
for (String cellName : getReservedCells()) {
Reservation reservation = currentCellReservation(cellName);
if (reservation != null &&
(reservation.time + reservation.duration * MINUTE) < now) {
try {
returnCell(reservation.userName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
|
warden-legacy-java/src/main/java/org/onlab/warden/Warden.java
|
/*
* Copyright 2016 Open Networking 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 implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onlab.warden;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.*;
/**
* Warden for tracking use of shared test cells.
*/
class Warden {
private static final String CELL_NOT_NULL = "Cell name cannot be null";
private static final String USER_NOT_NULL = "User name cannot be null";
private static final String KEY_NOT_NULL = "User key cannot be null";
private static final String UTF_8 = "UTF-8";
private static final long TIMEOUT = 10; // 10 seconds
private static final int MAX_MINUTES = 1_440; // 24 hours max
private static final int MINUTE = 60_000; // 1 minute
private static final int DEFAULT_MINUTES = 120; // 2 hours
private static final String DEFAULT_SPEC = "3+1";
private static final String SSH_COMMAND = "ssh -o ConnectTimeout=5";
private final File log = new File("warden.log");
// Allow overriding these for unit tests.
static String cmdPrefix = "";
static File root = new File(".");
private final File cells = new File(root, "cells");
private final File supported = new File(cells, "supported");
private final File reserved = new File(cells, "reserved");
private final Random random = new Random();
/**
* Creates a new cell warden.
*/
Warden() {
if (reserved.mkdirs()) {
System.out.println("Created " + reserved + " directory");
}
random.setSeed(System.currentTimeMillis());
Timer timer = new Timer("cell-pruner", true);
timer.schedule(new Reposessor(), MINUTE / 4, MINUTE / 2);
}
/**
* Returns list of names of supported cells.
*
* @return list of cell names
*/
Set<String> getCells() {
String[] list = supported.list();
return list != null ? ImmutableSet.copyOf(list) : ImmutableSet.of();
}
/**
* Returns list of names of available cells.
*
* @return list of cell names
*/
Set<String> getAvailableCells() {
Set<String> available = new HashSet<>(getCells());
available.removeAll(getReservedCells());
return ImmutableSet.copyOf(available);
}
/**
* Returns list of names of reserved cells.
*
* @return list of cell names
*/
Set<String> getReservedCells() {
String[] list = reserved.list();
return list != null ? ImmutableSet.copyOf(list) : ImmutableSet.of();
}
/**
* Returns the host name on which the specified cell is hosted.
*
* @param cellName cell name
* @return host name where the cell runs
*/
String getCellHost(String cellName) {
return getCellInfo(cellName).hostName;
}
/**
* Returns reservation for the specified user.
*
* @param userName user name
* @return cell reservation record or null if user does not have one
*/
Reservation currentUserReservation(String userName) {
checkNotNull(userName, USER_NOT_NULL);
for (String cellName : getReservedCells()) {
Reservation reservation = currentCellReservation(cellName);
if (reservation != null && userName.equals(reservation.userName)) {
return reservation;
}
}
return null;
}
/**
* Returns the name of the user who reserved the given cell.
*
* @param cellName cell name
* @return cell reservation record or null if cell is not reserved
*/
Reservation currentCellReservation(String cellName) {
checkNotNull(cellName, CELL_NOT_NULL);
File cellFile = new File(reserved, cellName);
if (!cellFile.exists()) {
return null;
}
try (InputStream stream = new FileInputStream(cellFile)) {
return new Reservation(new String(ByteStreams.toByteArray(stream), "UTF-8"));
} catch (IOException e) {
throw new IllegalStateException("Unable to get current user for cell " + cellName, e);
}
}
/**
* Reserves a cell for the specified user and their public access key.
*
* @param userName user name
* @param sshKey user ssh public key
* @param minutes optional number of minutes for reservation
* @param cellSpec optional cell specification string
* @param cellNameHint optional cell name hint
* @return reserved cell definition
*/
synchronized String borrowCell(String userName, String sshKey, int minutes,
String cellSpec, String cellNameHint) {
checkNotNull(userName, USER_NOT_NULL);
checkArgument(userName.matches("[\\w.-]+"), "Invalid user name %s", userName);
checkNotNull(sshKey, KEY_NOT_NULL);
checkArgument(minutes <= MAX_MINUTES, "Number of minutes must be less than %d", MAX_MINUTES);
checkArgument(minutes >= 0, "Number of minutes must be non-negative");
checkArgument(cellSpec == null || cellSpec.matches("[\\d]\\+[0-1]"),
"Invalid cell spec string %s", cellSpec);
Reservation reservation = currentUserReservation(userName);
boolean alreadyReserved = reservation != null;
if (reservation == null) {
// If there is no reservation for the user, create one
String cellName = findAvailableCell(cellNameHint);
reservation = new Reservation(cellName, userName, System.currentTimeMillis(),
minutes == 0 ? DEFAULT_MINUTES : minutes,
cellSpec == null ? DEFAULT_SPEC : cellSpec);
} else if (minutes == 0) {
// If minutes are 0, simply return the cell definition
return getCellDefinition(reservation.cellName);
} else {
// If minutes are > 0, update the existing cell reservation
reservation = new Reservation(reservation.cellName, userName,
System.currentTimeMillis(), minutes,
reservation.cellSpec);
}
reserveCell(reservation);
if (!alreadyReserved) {
createCell(reservation, sshKey);
}
log(userName, reservation.cellName, reservation.cellSpec,
"borrowed for " + reservation.duration + " minutes");
return getCellDefinition(reservation.cellName);
}
/**
* Returns name of an available cell. Cell is chosen based on the load
* of its hosting server; a random one will be chosen from the set of
* cells hosted by the least loaded server.
*
* @param cellNameHint optional hint for requesting a specific cell
* @return name of an available cell
*/
private String findAvailableCell(String cellNameHint) {
Set<String> cells = getAvailableCells();
checkState(!cells.isEmpty(), "No cells are presently available");
Map<String, ServerInfo> load = Maps.newHashMap();
cells.stream().map(this::getCellInfo)
.forEach(info -> load.compute(info.hostName, (k, v) -> v == null ?
new ServerInfo(info.hostName, info) : v.bumpLoad(info)));
if (cellNameHint != null && !cellNameHint.isEmpty() && cells.contains(cellNameHint)) {
return cellNameHint;
}
List<ServerInfo> servers = new ArrayList<>(load.values());
servers.sort((a, b) -> b.load - a.load);
for (ServerInfo server : servers) {
if (isAvailable(server)) {
return server.cells.get(random.nextInt(server.cells.size())).cellName;
}
}
throw new IllegalStateException("Unable to find available cell");
}
/**
* Determines whether the specified cell server is available.
*
* @param server cell server address
* @return true if available, false otherwise
*/
private boolean isAvailable(ServerInfo server) {
String key = Integer.toString(random.nextInt());
String result = exec(String.format("%s %s echo %s", SSH_COMMAND, server.hostName, key));
return result != null && result.contains(key);
}
/**
* Returns the specified cell for the specified user and their public access key.
*
* @param userName user name
*/
synchronized void returnCell(String userName) {
checkNotNull(userName, USER_NOT_NULL);
Reservation reservation = currentUserReservation(userName);
checkState(reservation != null, "User %s has no cell reservations", userName);
unreserveCell(reservation);
destroyCell(reservation);
log(userName, reservation.cellName, reservation.cellSpec, "returned");
}
/**
* Powers on/off the specified machine.
*
* @param userName user name (used for verification)
* @param nodeIp IP of the node to shutdown
* @param on true if node is to be powered on; false to power off
* @return summary of the command success or error
*/
String powerControl(String userName, String nodeIp, boolean on) {
checkNotNull(userName, USER_NOT_NULL);
Reservation reservation = currentUserReservation(userName);
checkState(reservation != null, "User %s has no cell reservations", userName);
CellInfo cellInfo = getCellInfo(reservation.cellName);
return exec(String.format("%s %s warden/bin/power-node %s %s %s", SSH_COMMAND,
cellInfo.hostName, cellInfo.cellName, nodeIp, on ? "on" : "off"));
}
/**
* Reserves the specified cell for the user the source file and writes the
* specified content to the target file.
*
* @param reservation cell reservation record
*/
private void reserveCell(Reservation reservation) {
File cellFile = new File(reserved, reservation.cellName);
try (FileOutputStream stream = new FileOutputStream(cellFile)) {
stream.write(reservation.encode().getBytes(UTF_8));
} catch (IOException e) {
throw new IllegalStateException("Unable to reserve cell " + reservation.cellName, e);
}
}
/**
* Returns the cell definition of the specified cell.
*
* @param cellName cell name
* @return cell definition
*/
private String getCellDefinition(String cellName) {
CellInfo cellInfo = getCellInfo(cellName);
return exec(String.format("%s %s warden/bin/cell-def %s",
SSH_COMMAND, cellInfo.hostName, cellInfo.cellName));
}
/**
* Cancels the specified reservation.
*
* @param reservation reservation record
*/
private void unreserveCell(Reservation reservation) {
checkState(new File(reserved, reservation.cellName).delete(),
"Unable to return cell %s", reservation.cellName);
}
/**
* Creates the cell for the specified user SSH key.
*
* @param reservation cell reservation
* @param sshKey ssh key
*/
private void createCell(Reservation reservation, String sshKey) {
CellInfo cellInfo = getCellInfo(reservation.cellName);
String cmd = String.format("%s %s warden/bin/create-cell %s %s %s %s",
SSH_COMMAND, cellInfo.hostName, cellInfo.cellName,
cellInfo.ipPrefix, reservation.cellSpec, sshKey);
exec(cmd);
}
/**
* Destroys the specified cell.
*
* @param reservation reservation record
*/
private void destroyCell(Reservation reservation) {
CellInfo cellInfo = getCellInfo(reservation.cellName);
exec(String.format("%s %s warden/bin/destroy-cell %s %s", SSH_COMMAND,
cellInfo.hostName, cellInfo.cellName, reservation.cellSpec));
}
/**
* Reads the information about the specified cell.
*
* @param cellName cell name
* @return cell information
*/
private CellInfo getCellInfo(String cellName) {
File cellFile = new File(supported, cellName);
try (InputStream stream = new FileInputStream(cellFile)) {
String[] fields = new String(ByteStreams.toByteArray(stream), UTF_8).split(" ");
return new CellInfo(cellName, fields[0], fields[1]);
} catch (IOException e) {
throw new IllegalStateException("Unable to definition for cell " + cellName, e);
}
}
// Executes the specified command.
private String exec(String command) {
try {
Process process = Runtime.getRuntime().exec(cmdPrefix + command);
String output = new String(ByteStreams.toByteArray(process.getInputStream()), UTF_8);
process.waitFor(TIMEOUT, TimeUnit.SECONDS);
return process.exitValue() == 0 ? output : null;
} catch (Exception e) {
throw new IllegalStateException("Unable to execute " + command);
}
}
// Creates an audit log entry.
private void log(String userName, String cellName, String cellSpec, String action) {
try (FileOutputStream fos = new FileOutputStream(log, true);
PrintWriter pw = new PrintWriter(fos)) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
pw.println(String.format("%s\t%s\t%s-%s\t%s", format.format(new Date()),
userName, cellName, cellSpec, action));
pw.flush();
} catch (IOException e) {
throw new IllegalStateException("Unable to log reservation action", e);
}
}
// Carrier of cell information
private final class CellInfo {
final String cellName;
final String hostName;
final String ipPrefix;
private CellInfo(String cellName, String hostName, String ipPrefix) {
this.cellName = cellName;
this.hostName = hostName;
this.ipPrefix = ipPrefix;
}
}
// Carrier of cell server information
private final class ServerInfo {
final String hostName;
boolean isAvailable = false;
int load = 0;
List<CellInfo> cells = Lists.newArrayList();
private ServerInfo(String hostName, CellInfo info) {
this.hostName = hostName;
bumpLoad(info);
}
private ServerInfo bumpLoad(CellInfo info) {
cells.add(info);
load++; // TODO: bump by cell size later
return this;
}
}
// Task for re-possessing overdue cells
private final class Reposessor extends TimerTask {
@Override
public void run() {
long now = System.currentTimeMillis();
for (String cellName : getReservedCells()) {
Reservation reservation = currentCellReservation(cellName);
if (reservation != null &&
(reservation.time + reservation.duration * MINUTE) < now) {
try {
returnCell(reservation.userName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
|
Add logging to powerControl function
|
warden-legacy-java/src/main/java/org/onlab/warden/Warden.java
|
Add logging to powerControl function
|
<ide><path>arden-legacy-java/src/main/java/org/onlab/warden/Warden.java
<ide> checkState(reservation != null, "User %s has no cell reservations", userName);
<ide>
<ide> CellInfo cellInfo = getCellInfo(reservation.cellName);
<add> log(userName, reservation.cellName, reservation.cellSpec,
<add> nodeIp + " powered " + on ? "on" : "off");
<ide> return exec(String.format("%s %s warden/bin/power-node %s %s %s", SSH_COMMAND,
<ide> cellInfo.hostName, cellInfo.cellName, nodeIp, on ? "on" : "off"));
<ide> }
|
|
Java
|
agpl-3.0
|
7f232eb261bc4a0245a0030e6f9b03be2ae54038
| 0 |
DragonsbaneProject/platform
|
package io.dragonsbane.neurocog.tests;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.dragonsbane.data.ImpairmentTest;
import io.dragonsbane.neurocog.DBApplication;
import io.dragonsbane.neurocog.R;
import io.onemfive.core.util.Numbers;
/**
* We can also do a more complex memory like 2 back which requires more attention.
* If I show you 6 bamboo, and then 3 wind, and then 3 wind you should not tap the screen,
* but if the last one is 6 bamboo, you should. We could even try 3 back.
*/
public class ComplexMemoryTestActivity extends ImpairmentTestActivity {
private int numberFlips = 12;
private int maxNumberDifferentCards = 3;
private int lastCardFlipped = 0;
private int secondToLastCardFlipped = 0;
private int currentCard = 0;
private int currentNumberFlips = 0;
// turn off screen from dimming so that we can check for all clicks even those that miss the card - gross motor
// impulsivity = reaction times when should not have clicked but did
private Long begin;
private Long end;
private List<Long> responseTimes = new ArrayList<>();
private int randomStartCardIndex;
private boolean isBackOfCardShowing = true;
private boolean shouldClick = false;
private boolean clickedWhenShould = false;
private FlipCard flipCard;
private EndTest endTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
randomStartCardIndex = Numbers.randomNumber(0, (DBApplication.cards.length-1)-maxNumberDifferentCards);
test = new ImpairmentTest(did, BORDERLINE_IMPAIRMENT);
test.setTimeStarted(new Date().getTime());
setContentView(R.layout.activity_complex_memory_test);
Toolbar toolbar = findViewById(R.id.action_bar);
TextView titleTextView = (TextView) toolbar.getChildAt(0);
titleTextView.setTextColor(getResources().getColor(R.color.dragonsbaneBlack));
titleTextView.setTypeface(((DBApplication)getApplication()).getNexaBold());
flipCard = new FlipCard();
new Handler().postDelayed(flipCard, normalFlipDurationMs); // flip card after 3 seconds
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void clickCard(View v) {
end = new Date().getTime();
long diff = end - begin;
if(isBackOfCardShowing) {
test.addInappropriate(diff);
} else if(!shouldClick) {
test.addMiss(diff);
} else {
clickedWhenShould = true;
test.addSuccess(diff);
flipCard.deactivate(); // Deactivate prior FlipCard
v.setEnabled(false);
v.clearAnimation();
v.setAnimation(animation1);
v.startAnimation(animation1);
}
}
@Override
public void onAnimationStart(Animation animation) {
if(animation == animation1) {
if(!isBackOfCardShowing && shouldClick && !clickedWhenShould) {
// Should have clicked and did not
test.addMiss(normalFlipDurationMs);
}
} else {
// Flip back status
isBackOfCardShowing = !isBackOfCardShowing;
if(isBackOfCardShowing) {
(findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(R.drawable.card_back));
} else {
// Face is showing
// Set second to last card flipped as last card flipped
secondToLastCardFlipped = lastCardFlipped;
// Set last card flipped as current card
lastCardFlipped = currentCard;
// Assign current card a new random card
currentCard = ((DBApplication)getApplicationContext()).getRandomCard(randomStartCardIndex, randomStartCardIndex + maxNumberDifferentCards);
(findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(currentCard));
// Save card to test cards used if it doesn't already contain it
if(!test.getCardsUsed().contains(currentCard)) test.getCardsUsed().add(currentCard);
// Determine if this current card should be clicked
shouldClick = currentCard == secondToLastCardFlipped;
clickedWhenShould = false;
numberFlips--;
findViewById(R.id.complexMemoryTestCard).setEnabled(true);
begin = new Date().getTime();
}
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (animation == animation1) {
// End of 1st half of flip
(findViewById(R.id.complexMemoryTestCard)).clearAnimation();
(findViewById(R.id.complexMemoryTestCard)).setAnimation(animation2);
(findViewById(R.id.complexMemoryTestCard)).startAnimation(animation2);
} else {
// animation2 - End of 2nd half of flip
if(isBackOfCardShowing) {
// back showing
if (numberFlips > 0) {
flipCard = new FlipCard();
new Handler().postDelayed(flipCard, shortFlipDuractionMs); // flip card after 1 second
} else {
endTest.deactivate(); // Clicked; deactive previous endTest
endTest = new EndTest();
new Handler().postDelayed(endTest, shortFlipDuractionMs); // end test after 1 second
}
} else {
// face card showing
if( numberFlips > 0) {
flipCard = new FlipCard();
new Handler().postDelayed(flipCard, normalFlipDurationMs); // flip card after 3 seconds
} else {
endTest = new EndTest();
new Handler().postDelayed(endTest, normalFlipDurationMs); // end test after 3 seconds if not clicked
}
}
}
}
private class FlipCard implements Runnable {
private boolean active = true;
public void deactivate() {
active = false;
}
@Override
public void run() {
// Flip the card
if(active) {
ImageView v = findViewById(R.id.complexMemoryTestCard);
v.setEnabled(false);
v.clearAnimation();
v.setAnimation(animation1);
v.startAnimation(animation1);
currentNumberFlips++;
}
}
}
private class EndTest implements Runnable {
private boolean active = true;
public void deactivate() {
active = false;
}
@Override
public void run() {
if(active) {
findViewById(R.id.complexMemoryTestCard).setVisibility(View.INVISIBLE);
testFinished();
findViewById(R.id.complexMemoryButtonNextTest).setVisibility(View.VISIBLE);
findViewById(R.id.resultsLayout).setVisibility(View.VISIBLE);
// Successes
((TextView)findViewById(R.id.resultsTotalSuccess)).setText(String.valueOf(test.getSuccesses().size()));
((TextView)findViewById(R.id.resultsMinSuccess)).setText(String.valueOf(test.getMinResponseTimeSuccessMs()));
((TextView)findViewById(R.id.resultsMaxSuccess)).setText(String.valueOf(test.getMaxResponseTimeSuccessMs()));
((TextView)findViewById(R.id.resultsAvgSuccess)).setText(String.valueOf(test.getAvgResponseTimeSuccessMs()));
// Misses
((TextView)findViewById(R.id.resultsTotalMisses)).setText(String.valueOf(test.getMisses().size()));
((TextView)findViewById(R.id.resultsMinMisses)).setText(String.valueOf(test.getMinResponseTimeMissMs()));
((TextView)findViewById(R.id.resultsMaxMisses)).setText(String.valueOf(test.getMaxResponseTimeMissMs()));
((TextView)findViewById(R.id.resultsAvgMisses)).setText(String.valueOf(test.getAvgResponseTimeMissMs()));
// Negative
((TextView)findViewById(R.id.resultsTotalNegative)).setText(String.valueOf(test.getNegatives().size()));
((TextView)findViewById(R.id.resultsMinNegative)).setText(String.valueOf(test.getMinResponseTimeNegativeMs()));
((TextView)findViewById(R.id.resultsMaxNegative)).setText(String.valueOf(test.getMaxResponseTimeNegativeMs()));
((TextView)findViewById(R.id.resultsAvgNegative)).setText(String.valueOf(test.getAvgResponseTimeNegativeMs()));
// Inappropriate
((TextView)findViewById(R.id.resultsTotalInappropriate)).setText(String.valueOf(test.getInappropriates().size()));
((TextView)findViewById(R.id.resultsMinInappropriate)).setText(String.valueOf(test.getMinResponseTimeInappropriateMs()));
((TextView)findViewById(R.id.resultsMaxInappropriate)).setText(String.valueOf(test.getMaxResponseTimeInappropriateMs()));
((TextView)findViewById(R.id.resultsAvgInappropriate)).setText(String.valueOf(test.getAvgResponseTimeInappropriateMs()));
}
}
}
public void nextTest(View view) {
Intent intent = new Intent(this, WorkingMemoryTestActivity.class);
startActivity(intent);
}
}
|
app/src/main/java/io/dragonsbane/neurocog/tests/ComplexMemoryTestActivity.java
|
package io.dragonsbane.neurocog.tests;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.dragonsbane.data.ImpairmentTest;
import io.dragonsbane.neurocog.DBApplication;
import io.dragonsbane.neurocog.R;
import io.onemfive.core.util.Numbers;
/**
* We can also do a more complex memory like 2 back which requires more attention.
* If I show you 6 bamboo, and then 3 wind, and then 3 wind you should not tap the screen,
* but if the last one is 6 bamboo, you should. We could even try 3 back.
*/
public class ComplexMemoryTestActivity extends ImpairmentTestActivity {
private int numberFlips = 12;
private int maxNumberDifferentCards = 3;
private int lastCardFlipped = 0;
private int secondToLastCardFlipped = 0;
private int currentCard = 0;
private int currentNumberFlips = 0;
// turn off screen from dimming so that we can check for all clicks even those that miss the card - gross motor
// impulsivity = reaction times when should not have clicked but did
private Long begin;
private Long end;
private List<Long> responseTimes = new ArrayList<>();
private int randomStartCardIndex;
private boolean isBackOfCardShowing = true;
private boolean shouldNotClick = false;
private FlipCard flipCard;
private EndTest endTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
randomStartCardIndex = Numbers.randomNumber(0, (DBApplication.cards.length-1)-maxNumberDifferentCards);
test = new ImpairmentTest(did, BORDERLINE_IMPAIRMENT);
test.setTimeStarted(new Date().getTime());
setContentView(R.layout.activity_complex_memory_test);
Toolbar toolbar = findViewById(R.id.action_bar);
TextView titleTextView = (TextView) toolbar.getChildAt(0);
titleTextView.setTextColor(getResources().getColor(R.color.dragonsbaneBlack));
titleTextView.setTypeface(((DBApplication)getApplication()).getNexaBold());
flipCard = new FlipCard();
new Handler().postDelayed(flipCard, normalFlipDurationMs); // flip card after 3 seconds
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void clickCard(View v) {
end = new Date().getTime();
test.setTimeEnded(end);
long diff = end - begin;
if(isBackOfCardShowing) {
test.addInappropriate(diff);return;}
if(shouldNotClick) {
test.addMiss(diff);return;}
test.addSuccess(diff);
flipCard.deactivate(); // Deactivate prior FlipCard
v.setEnabled(false);
v.clearAnimation();
v.setAnimation(animation1);
v.startAnimation(animation1);
}
@Override
public void onAnimationStart(Animation animation) {
if(animation == animation1 && !isBackOfCardShowing && !shouldNotClick) {
// Should have clicked and did not
test.addMiss(normalFlipDurationMs);
}
if (animation == animation2) {
if(isBackOfCardShowing) {
begin = new Date().getTime();
test.setTimeStarted(begin);
}
}
}
@Override
public void onAnimationEnd(Animation animation) {
if (animation == animation1) {
// End of 1st half of flip
if (isBackOfCardShowing) {
numberFlips--;
secondToLastCardFlipped = lastCardFlipped;
lastCardFlipped = currentCard;
currentCard = ((DBApplication)getApplicationContext()).getRandomCard(randomStartCardIndex, randomStartCardIndex + maxNumberDifferentCards);
shouldNotClick = currentCard != secondToLastCardFlipped;
if(!test.getCardsUsed().contains(currentCard)) test.getCardsUsed().add(currentCard);
(findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(currentCard));
} else {
(findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(R.drawable.card_back));
}
(findViewById(R.id.complexMemoryTestCard)).clearAnimation();
(findViewById(R.id.complexMemoryTestCard)).setAnimation(animation2);
(findViewById(R.id.complexMemoryTestCard)).startAnimation(animation2);
} else {
// animation2 - End of 2nd half of flip
isBackOfCardShowing=!isBackOfCardShowing;
findViewById(R.id.complexMemoryTestCard).setEnabled(true);
if(!isBackOfCardShowing) {
// face card showing
if( numberFlips > 0) {
flipCard = new FlipCard();
new Handler().postDelayed(flipCard, normalFlipDurationMs); // flip card after 3 seconds
} else {
endTest = new EndTest();
new Handler().postDelayed(endTest, normalFlipDurationMs); // end test after 3 seconds if not clicked
}
} else {
// back showing
if( numberFlips > 0) {
flipCard = new FlipCard();
new Handler().postDelayed(flipCard, shortFlipDuractionMs); // flip card after 1 second
} else {
endTest.deactivate(); // Clicked; deactive previous endTest
endTest = new EndTest();
new Handler().postDelayed(endTest, shortFlipDuractionMs); // end test after 1 second
}
}
}
}
private class FlipCard implements Runnable {
private boolean active = true;
public void deactivate() {
active = false;
}
@Override
public void run() {
// Flip the card
if(active) {
ImageView v = findViewById(R.id.complexMemoryTestCard);
v.setEnabled(false);
v.clearAnimation();
v.setAnimation(animation1);
v.startAnimation(animation1);
currentNumberFlips++;
}
}
}
private class EndTest implements Runnable {
private boolean active = true;
public void deactivate() {
active = false;
}
@Override
public void run() {
if(active) {
findViewById(R.id.complexMemoryTestCard).setVisibility(View.INVISIBLE);
findViewById(R.id.complexMemoryButtonNextTest).setVisibility(View.VISIBLE);
findViewById(R.id.resultsLayout).setVisibility(View.VISIBLE);
// Successes
((TextView)findViewById(R.id.resultsTotalSuccess)).setText(String.valueOf(test.getSuccesses().size()));
((TextView)findViewById(R.id.resultsMinSuccess)).setText(String.valueOf(test.getMinResponseTimeSuccessMs()));
((TextView)findViewById(R.id.resultsMaxSuccess)).setText(String.valueOf(test.getMaxResponseTimeSuccessMs()));
((TextView)findViewById(R.id.resultsAvgSuccess)).setText(String.valueOf(test.getAvgResponseTimeSuccessMs()));
// Misses
((TextView)findViewById(R.id.resultsTotalMisses)).setText(String.valueOf(test.getMisses().size()));
((TextView)findViewById(R.id.resultsMinMisses)).setText(String.valueOf(test.getMinResponseTimeMissMs()));
((TextView)findViewById(R.id.resultsMaxMisses)).setText(String.valueOf(test.getMaxResponseTimeMissMs()));
((TextView)findViewById(R.id.resultsAvgMisses)).setText(String.valueOf(test.getAvgResponseTimeMissMs()));
// Negative
((TextView)findViewById(R.id.resultsTotalNegative)).setText(String.valueOf(test.getNegatives().size()));
((TextView)findViewById(R.id.resultsMinNegative)).setText(String.valueOf(test.getMinResponseTimeNegativeMs()));
((TextView)findViewById(R.id.resultsMaxNegative)).setText(String.valueOf(test.getMaxResponseTimeNegativeMs()));
((TextView)findViewById(R.id.resultsAvgNegative)).setText(String.valueOf(test.getAvgResponseTimeNegativeMs()));
// Inappropriate
((TextView)findViewById(R.id.resultsTotalInappropriate)).setText(String.valueOf(test.getInappropriates().size()));
((TextView)findViewById(R.id.resultsMinInappropriate)).setText(String.valueOf(test.getMinResponseTimeInappropriateMs()));
((TextView)findViewById(R.id.resultsMaxInappropriate)).setText(String.valueOf(test.getMaxResponseTimeInappropriateMs()));
((TextView)findViewById(R.id.resultsAvgInappropriate)).setText(String.valueOf(test.getAvgResponseTimeInappropriateMs()));
}
}
}
public void nextTest(View view) {
Intent intent = new Intent(this, WorkingMemoryTestActivity.class);
startActivity(intent);
}
}
|
working properly with successes
|
app/src/main/java/io/dragonsbane/neurocog/tests/ComplexMemoryTestActivity.java
|
working properly with successes
|
<ide><path>pp/src/main/java/io/dragonsbane/neurocog/tests/ComplexMemoryTestActivity.java
<ide> private int randomStartCardIndex;
<ide>
<ide> private boolean isBackOfCardShowing = true;
<del> private boolean shouldNotClick = false;
<add> private boolean shouldClick = false;
<add> private boolean clickedWhenShould = false;
<ide>
<ide> private FlipCard flipCard;
<ide> private EndTest endTest;
<ide>
<ide> public void clickCard(View v) {
<ide> end = new Date().getTime();
<del> test.setTimeEnded(end);
<ide> long diff = end - begin;
<ide> if(isBackOfCardShowing) {
<del> test.addInappropriate(diff);return;}
<del> if(shouldNotClick) {
<del> test.addMiss(diff);return;}
<del> test.addSuccess(diff);
<del>
<del> flipCard.deactivate(); // Deactivate prior FlipCard
<del> v.setEnabled(false);
<del> v.clearAnimation();
<del> v.setAnimation(animation1);
<del> v.startAnimation(animation1);
<add> test.addInappropriate(diff);
<add> } else if(!shouldClick) {
<add> test.addMiss(diff);
<add> } else {
<add> clickedWhenShould = true;
<add> test.addSuccess(diff);
<add> flipCard.deactivate(); // Deactivate prior FlipCard
<add> v.setEnabled(false);
<add> v.clearAnimation();
<add> v.setAnimation(animation1);
<add> v.startAnimation(animation1);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void onAnimationStart(Animation animation) {
<del> if(animation == animation1 && !isBackOfCardShowing && !shouldNotClick) {
<del> // Should have clicked and did not
<del> test.addMiss(normalFlipDurationMs);
<del> }
<del> if (animation == animation2) {
<add> if(animation == animation1) {
<add> if(!isBackOfCardShowing && shouldClick && !clickedWhenShould) {
<add> // Should have clicked and did not
<add> test.addMiss(normalFlipDurationMs);
<add> }
<add> } else {
<add> // Flip back status
<add> isBackOfCardShowing = !isBackOfCardShowing;
<ide> if(isBackOfCardShowing) {
<add> (findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(R.drawable.card_back));
<add> } else {
<add> // Face is showing
<add> // Set second to last card flipped as last card flipped
<add> secondToLastCardFlipped = lastCardFlipped;
<add> // Set last card flipped as current card
<add> lastCardFlipped = currentCard;
<add> // Assign current card a new random card
<add> currentCard = ((DBApplication)getApplicationContext()).getRandomCard(randomStartCardIndex, randomStartCardIndex + maxNumberDifferentCards);
<add> (findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(currentCard));
<add> // Save card to test cards used if it doesn't already contain it
<add> if(!test.getCardsUsed().contains(currentCard)) test.getCardsUsed().add(currentCard);
<add> // Determine if this current card should be clicked
<add> shouldClick = currentCard == secondToLastCardFlipped;
<add> clickedWhenShould = false;
<add> numberFlips--;
<add> findViewById(R.id.complexMemoryTestCard).setEnabled(true);
<ide> begin = new Date().getTime();
<del> test.setTimeStarted(begin);
<ide> }
<ide> }
<ide> }
<ide> public void onAnimationEnd(Animation animation) {
<ide> if (animation == animation1) {
<ide> // End of 1st half of flip
<del> if (isBackOfCardShowing) {
<del> numberFlips--;
<del> secondToLastCardFlipped = lastCardFlipped;
<del> lastCardFlipped = currentCard;
<del> currentCard = ((DBApplication)getApplicationContext()).getRandomCard(randomStartCardIndex, randomStartCardIndex + maxNumberDifferentCards);
<del> shouldNotClick = currentCard != secondToLastCardFlipped;
<del> if(!test.getCardsUsed().contains(currentCard)) test.getCardsUsed().add(currentCard);
<del> (findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(currentCard));
<del> } else {
<del> (findViewById(R.id.complexMemoryTestCard)).setBackground(getResources().getDrawable(R.drawable.card_back));
<del> }
<ide> (findViewById(R.id.complexMemoryTestCard)).clearAnimation();
<ide> (findViewById(R.id.complexMemoryTestCard)).setAnimation(animation2);
<ide> (findViewById(R.id.complexMemoryTestCard)).startAnimation(animation2);
<ide> } else {
<ide> // animation2 - End of 2nd half of flip
<del> isBackOfCardShowing=!isBackOfCardShowing;
<del> findViewById(R.id.complexMemoryTestCard).setEnabled(true);
<del> if(!isBackOfCardShowing) {
<add> if(isBackOfCardShowing) {
<add> // back showing
<add> if (numberFlips > 0) {
<add> flipCard = new FlipCard();
<add> new Handler().postDelayed(flipCard, shortFlipDuractionMs); // flip card after 1 second
<add> } else {
<add> endTest.deactivate(); // Clicked; deactive previous endTest
<add> endTest = new EndTest();
<add> new Handler().postDelayed(endTest, shortFlipDuractionMs); // end test after 1 second
<add> }
<add> } else {
<ide> // face card showing
<ide> if( numberFlips > 0) {
<ide> flipCard = new FlipCard();
<ide> } else {
<ide> endTest = new EndTest();
<ide> new Handler().postDelayed(endTest, normalFlipDurationMs); // end test after 3 seconds if not clicked
<del> }
<del> } else {
<del> // back showing
<del> if( numberFlips > 0) {
<del> flipCard = new FlipCard();
<del> new Handler().postDelayed(flipCard, shortFlipDuractionMs); // flip card after 1 second
<del> } else {
<del> endTest.deactivate(); // Clicked; deactive previous endTest
<del> endTest = new EndTest();
<del> new Handler().postDelayed(endTest, shortFlipDuractionMs); // end test after 1 second
<ide> }
<ide> }
<ide> }
<ide> public void run() {
<ide> if(active) {
<ide> findViewById(R.id.complexMemoryTestCard).setVisibility(View.INVISIBLE);
<add> testFinished();
<ide> findViewById(R.id.complexMemoryButtonNextTest).setVisibility(View.VISIBLE);
<ide> findViewById(R.id.resultsLayout).setVisibility(View.VISIBLE);
<ide>
|
|
Java
|
lgpl-2.1
|
720f0ccbd81180d33aa49b8960740a8cd62c4c84
| 0 |
baranovRP/functional-tests,TheNoise/functional-tests,jtalks-org/functional-tests,dmitryakushev/JTalks,DentonA/functional-tests
|
/**
* Copyright (C) 2011 JTalks.org Team
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jtalks.tests.jcommune.webdriver.action;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.jtalks.tests.jcommune.webdriver.entity.branch.Branch;
import org.jtalks.tests.jcommune.webdriver.entity.topic.Poll;
import org.jtalks.tests.jcommune.webdriver.entity.topic.Post;
import org.jtalks.tests.jcommune.webdriver.entity.topic.Topic;
import org.jtalks.tests.jcommune.webdriver.entity.user.User;
import org.jtalks.tests.jcommune.webdriver.exceptions.CouldNotOpenPageException;
import org.jtalks.tests.jcommune.webdriver.exceptions.PermissionsDeniedException;
import org.jtalks.tests.jcommune.webdriver.exceptions.ValidationException;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.jtalks.tests.jcommune.utils.StringHelp.randomString;
import static org.jtalks.tests.jcommune.webdriver.page.Pages.branchPage;
import static org.jtalks.tests.jcommune.webdriver.page.Pages.postPage;
import static org.jtalks.tests.jcommune.webdriver.page.Pages.topicPage;
/**
* Contain topic actions like creating, deleting etc.
*
* @author Guram Savinov
*/
public class Topics {
private static final Logger LOGGER = LoggerFactory.getLogger(Topics.class);
private static final String POLL_END_DATE_FORMAT = "dd-MM-yyyy";
/**
* Sign-up new user and create new topic
*
* @param topic the topic representation private static final String POLL_END_DATE_FORMAT = "dd-MM-yyyy";
* <p/>
* /** Signs-up up a new random user and creates the topic in the first available branch.
* @throws ValidationException if specified topic does not pass forum validation
* @throws PermissionsDeniedException if use cannot post in the first visible branch, she has no permissions
*/
public static void signUpAndCreateTopic(Topic topic) throws ValidationException, PermissionsDeniedException {
User user = Users.signUp();
Users.signIn(user);
topic.withTopicStarter(user);
createTopic(topic);
}
public static Topic loginAndCreateTopic(Topic topic) throws ValidationException, PermissionsDeniedException {
User existentUser = new User("P_10hkgd", "123456");
topic.withTopicStarter(existentUser);
Users.signIn(existentUser);
return createTopic(topic);
}
public static Boolean isBranch(Topic topic) {
boolean isBranch = false;
Branches.openBranch(topic.getBranch().getTitle());
openTopicInCurrentBranch(100, topic.getTitle());
return isBranch;
}
public static boolean isInCorrectBranch(Topic topic) {
return topicPage.getBranchName().getText().trim().equals(topic.getBranch().getTitle());
}
public static boolean isTopicNewer(DateTime topicDate, String dateFromLastRow) {
DateTimeFormatter mask = new DateTimeFormatterBuilder()
.appendDayOfMonth(2)
.appendLiteral(' ')
.appendMonthOfYearShortText()
.appendLiteral(' ')
.appendYear(4, 4)
.appendLiteral(' ')
.appendHourOfDay(2)
.appendLiteral(':')
.appendMinuteOfHour(2)
.toFormatter();
DateTime dat = DateTime.parse(dateFromLastRow, mask);
return topicDate.isAfter(dat.getMillis());
}
/**
* Creates new topic. If {@link Topic#getBranch()} is null, then topic is created in a random branch,
* otherwise the topic is created in a {@link Topic#getBranch()}.
*
* @throws PermissionsDeniedException if use cannot post in the first visible branch, she has no permissions
* @throws CouldNotOpenPageException if user was not able to find and open a branch with the specified name
*/
public static Topic createTopic(Topic topic) throws PermissionsDeniedException, CouldNotOpenPageException {
if (topic.getBranch() == null) {
Branch branch = new Branch(branchPage.getBranchList().get(0).getText());
topic.withBranch(branch);
}
Branches.openBranch(topic.getBranch().getTitle());
clickCreateTopic();
fillTopicFields(topic);
fillPollSpecificFields(topic.getPoll());
clickAnswerToTopicButton(topic);
topic.setModificationDate(org.joda.time.DateTime.now().plusMinutes(1));
return topic;
}
public static void createCodeReview(Topic topic) throws PermissionsDeniedException, CouldNotOpenPageException {
if (topic.getBranch() == null) {
Branch branch = new Branch(branchPage.getBranchList().get(0).getText());
topic.withBranch(branch);
}
Branches.openBranch(topic.getBranch().getTitle());
createNewCodeReview(topic);
}
private static void createNewCodeReview(Topic topic) {
topicPage.getNewCodeReviewButton().click();
topicPage.getSubjectField().sendKeys(topic.getTitle());
Post firstPost = topic.getPosts().get(0);
topicPage.getMainBodyArea().sendKeys(firstPost.getPostContent());
topicPage.getPostButton().click();
}
public static void postAnswer(Topic topic, String branchTitle)
throws PermissionsDeniedException, CouldNotOpenPageException, InterruptedException {
//TODO: this might need to be uncommented, but right now we're not on the main page when we answer to the
// topic - we are on the topic page already!
// Branches.openBranch(branchTitle);
// if (openTopicInCurrentBranch(100, topic.getTitle())) {
answerToTopic(topic, topic.getLastPost().getPostContent());
LOGGER.info("postAnswerToTopic {}", topic.getTitle());
// }
}
private static boolean findTopic(String topicTitle) throws CouldNotOpenPageException {
boolean found = false;
for (WebElement topics : topicPage.getTopicsList()) {
if (topics.getText().trim().equals(topicTitle.trim())) {
topics.click();
found = true;
break;
}
}
return found;
}
private static boolean findTopic(Topic topic) throws CouldNotOpenPageException {
boolean found = false;
for (WebElement topics : topicPage.getTopicsList()) {
if (topics.getText().trim().equals(topic.getTitle().trim())) {
topics.click();
found = true;
break;
}
}
return found;
}
private static void answerToTopic(Topic topic, String answer) throws PermissionsDeniedException {
postPage.getNewButton().click();
topicPage.getMainBodyArea().sendKeys(answer);
clickAnswerToTopicButton(topic);
}
/**
* Looks through several pages of the branch in order to find the topic with the specified id.
*
* @param numberOfPagesToCheck since the topic might not be on the first page (either someone simultaneously creates
* a lot of topics, or there are a lot of sticked topics), we have to iteration through
* this number of pages to search for the topic
* @param topicToFind a topic id to look for
* @return true if the specified topic was found
* @throws CouldNotOpenPageException if specified topic was not found
*/
private static boolean openTopicInCurrentBranch(int numberOfPagesToCheck, String topicToFind)
throws CouldNotOpenPageException {
boolean found;
while (!(found = findTopic(topicToFind))) {
if (!openNextPage(numberOfPagesToCheck)) break;
}
if (!found) {
LOGGER.info("No topic with title [{}] found", topicToFind);
throw new CouldNotOpenPageException(topicToFind);
}
return found;
}
private static boolean openNextPage(int pagesToCheck) {
int max = 0;
if (topicPage.getActiveTopicsButton().size() < 1) {
return false;
}
WebElement activeBtn = topicPage.getActiveTopicsButton().get(0);
int active = Integer.parseInt(activeBtn.getText().trim());
for (WebElement el : topicPage.getTopicsButtons()) {
if (Integer.parseInt(el.getText().trim()) > max)
max = Integer.parseInt(el.getText().trim());
}
if ((active < pagesToCheck) && (active < max)) {
for (WebElement elem : topicPage.getTopicsButtons()) {
if (Integer.parseInt(elem.getText().trim()) == (active + 1)) {
elem.click();
return true;
}
}
}
return false;
}
public static boolean senseToPageNext(Topic topic) {
WebElement bottomRowOfTopics = topicPage.getLastTopicLine();
System.out.println(bottomRowOfTopics.getText());
System.out.println(bottomRowOfTopics.findElement(By.className("sticky")).getText());
System.out.println("Topic date is " + topic.getModificationDate());
//if (bottomRowOfTopics.findElements(By.xpath("*/span[contains(@class,'sticky')]")).size()>0) return true;
String dateFromBottomRowOfTopics = bottomRowOfTopics.findElement(By.xpath("*/a[contains(@class,'date')]")).getText().trim();
return isTopicNewer(DateTime.now(), dateFromBottomRowOfTopics);
}
/**
* Sets state for checkbox element
*
* @param checkboxElement the checkbox web element
* @param state the state: true - checked, false - unchecked, null - the element is not used
*/
private static void setCheckboxState(WebElement checkboxElement, Boolean state) {
if (state == null) {
return;
}
if (state && !checkboxElement.isSelected()) {
checkboxElement.click();
} else if (!state && checkboxElement.isSelected()) {
checkboxElement.click();
}
}
/**
* Sets the end date in the poll.
*
* @param poll the poll.
*/
private static void setPollsEndDate(Poll poll) {
String date;
if ((date = dateToString(poll.getEndDate(), POLL_END_DATE_FORMAT)) != null) {
topicPage.getTopicsPollEndDateField().sendKeys(date);
}
}
/**
* Returns date in string type.
*
* @param date the date.
* @param format the format of date in string.
* @return the date in the string.
*/
private static void clickAnswerToTopicButton(Topic topic) throws PermissionsDeniedException {
try {
topicPage.getPostButton().click();
} catch (NoSuchElementException e) {
throw new PermissionsDeniedException("User does not have permissions to leave posts in branch "
+ topic.getBranch().getTitle());
}
}
private static void fillPollSpecificFields(Poll poll) {
if (poll != null) {
topicPage.getTopicPollTitleField().sendKeys(poll.getTitle());
WebElement optionsField = topicPage.getTopicPollItemsField();
for (String option : poll.getOptions()) {
optionsField.sendKeys(option + "\n");
}
setPollsEndDate(poll);
setCheckboxState(topicPage.getTopicsPollMultipleChecker(), poll.isMultipleAnswers());
}
}
private static void fillTopicFields(Topic topic) {
setCheckboxState(topicPage.getTopicSticked(), topic.getSticked());
setCheckboxState(topicPage.getTopicAnnouncement(), topic.getAnnouncement());
topicPage.getSubjectField().sendKeys(!topic.getTitle().equals("") ? topic.getTitle() : randomString(15));
topicPage.getMainBodyArea().sendKeys(topic.getFirstPost().getPostContent());
}
private static void clickCreateTopic() throws PermissionsDeniedException {
try {
topicPage.getNewButton().click();
} catch (NoSuchElementException e) {
throw new PermissionsDeniedException();
}
}
/**
* Returns date in string type.
*
* @param date the date.
* @param format the format of date in string.
* @return the date in the string.
*/
private static String dateToString(Date date, String format) {
if (date != null) {
return new SimpleDateFormat(format).format(date);
}
return null;
}
/**
* Create new topic
*
* @param topic
* the topic representation
* @throws PermissionsDeniedException
*/
}
|
jcommune-webdriver/src/main/java/org/jtalks/tests/jcommune/webdriver/action/Topics.java
|
/**
* Copyright (C) 2011 JTalks.org Team
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jtalks.tests.jcommune.webdriver.action;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.jtalks.tests.jcommune.webdriver.entity.branch.Branch;
import org.jtalks.tests.jcommune.webdriver.entity.topic.Poll;
import org.jtalks.tests.jcommune.webdriver.entity.topic.Post;
import org.jtalks.tests.jcommune.webdriver.entity.topic.Topic;
import org.jtalks.tests.jcommune.webdriver.entity.user.User;
import org.jtalks.tests.jcommune.webdriver.exceptions.CouldNotOpenPageException;
import org.jtalks.tests.jcommune.webdriver.exceptions.PermissionsDeniedException;
import org.jtalks.tests.jcommune.webdriver.exceptions.ValidationException;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.jtalks.tests.jcommune.utils.StringHelp.randomString;
import static org.jtalks.tests.jcommune.webdriver.page.Pages.branchPage;
import static org.jtalks.tests.jcommune.webdriver.page.Pages.postPage;
import static org.jtalks.tests.jcommune.webdriver.page.Pages.topicPage;
/**
* Contain topic actions like creating, deleting etc.
*
* @author Guram Savinov
*/
public class Topics {
private static final Logger LOGGER = LoggerFactory.getLogger(Topics.class);
private static final String POLL_END_DATE_FORMAT = "dd-MM-yyyy";
/**
* Sign-up new user and create new topic
*
* @param topic the topic representation private static final String POLL_END_DATE_FORMAT = "dd-MM-yyyy";
* <p/>
* /** Signs-up up a new random user and creates the topic in the first available branch.
* @throws ValidationException if specified topic does not pass forum validation
* @throws PermissionsDeniedException if use cannot post in the first visible branch, she has no permissions
*/
public static void signUpAndCreateTopic(Topic topic) throws ValidationException, PermissionsDeniedException {
User user = Users.signUp();
Users.signIn(user);
topic.withTopicStarter(user);
createTopic(topic);
}
public static Topic loginAndCreateTopic(Topic topic) throws ValidationException, PermissionsDeniedException {
User existentUser = new User("P_10hkgd", "123456");
topic.withTopicStarter(existentUser);
Users.signIn(existentUser);
return createTopic(topic);
}
public static Boolean isBranch(Topic topic) {
boolean isBranch = false;
Branches.openBranch(topic.getBranch().getTitle());
openTopicInCurrentBranch(100, topic.getTitle());
return isBranch;
}
public static boolean isInCorrectBranch(Topic topic) {
return topicPage.getBranchName().getText().trim().equals(topic.getBranch().getTitle());
}
public static boolean isTopicNewer(DateTime topicDate, String dateFromLastRow) {
DateTimeFormatter mask = new DateTimeFormatterBuilder()
.appendDayOfMonth(2)
.appendLiteral(' ')
.appendMonthOfYearShortText()
.appendLiteral(' ')
.appendYear(4, 4)
.appendLiteral(' ')
.appendHourOfDay(2)
.appendLiteral(':')
.appendMinuteOfHour(2)
.toFormatter();
DateTime dat = DateTime.parse(dateFromLastRow, mask);
return topicDate.isAfter(dat.getMillis());
}
/**
* Creates new topic. If {@link Topic#getBranch()} is null, then topic is created in a random branch,
* otherwise the topic is created in a {@link Topic#getBranch()}.
*
* @throws PermissionsDeniedException if use cannot post in the first visible branch, she has no permissions
* @throws CouldNotOpenPageException if user was not able to find and open a branch with the specified name
*/
public static Topic createTopic(Topic topic) throws PermissionsDeniedException, CouldNotOpenPageException {
if (topic.getBranch() == null) {
Branch branch = new Branch(branchPage.getBranchList().get(0).getText());
topic.withBranch(branch);
}
Branches.openBranch(topic.getBranch().getTitle());
clickCreateTopic();
fillTopicFields(topic);
fillPollSpecificFields(topic.getPoll());
clickAnswerToTopicButton(topic);
topic.setModificationDate(org.joda.time.DateTime.now().plusMinutes(1));
return topic;
}
/**
* Create new topic
*
* @param topic the topic representation
* @throws PermissionsDeniedException
*/
/*
private static Topic createNewTopic(Topic topic) throws PermissionsDeniedException {
Branches.openBranch(topic.getBranch().getTitle());
clickCreateTopic();
fillTopicFields(topic);
fillPollSpecificFields(topic.getPoll());
clickAnswerToTopicButton(topic);
topic.setModificationDate(org.joda.time.DateTime.now().plusMinutes(1));
return topic;
}
*/
public static void createCodeReview(Topic topic) throws PermissionsDeniedException, CouldNotOpenPageException {
if (topic.getBranch() == null) {
Branch branch = new Branch(branchPage.getBranchList().get(0).getText());
topic.withBranch(branch);
}
Branches.openBranch(topic.getBranch().getTitle());
createNewCodeReview(topic);
}
private static void createNewCodeReview(Topic topic) {
topicPage.getNewCodeReviewButton().click();
topicPage.getSubjectField().sendKeys(topic.getTitle());
Post firstPost = topic.getPosts().get(0);
topicPage.getMainBodyArea().sendKeys(firstPost.getPostContent());
topicPage.getPostButton().click();
}
public static void postAnswer(Topic topic, String branchTitle)
throws PermissionsDeniedException, CouldNotOpenPageException, InterruptedException {
//TODO: this might need to be uncommented, but right now we're not on the main page when we answer to the
// topic - we are on the topic page already!
// Branches.openBranch(branchTitle);
// if (openTopicInCurrentBranch(100, topic.getTitle())) {
answerToTopic(topic, topic.getLastPost().getPostContent());
LOGGER.info("postAnswerToTopic {}", topic.getTitle());
// }
}
private static boolean findTopic(String topicTitle) throws CouldNotOpenPageException {
boolean found = false;
for (WebElement topics : topicPage.getTopicsList()) {
if (topics.getText().trim().equals(topicTitle.trim())) {
topics.click();
found = true;
break;
}
}
return found;
}
private static boolean findTopic(Topic topic) throws CouldNotOpenPageException {
boolean found = false;
for (WebElement topics : topicPage.getTopicsList()) {
if (topics.getText().trim().equals(topic.getTitle().trim())) {
topics.click();
found = true;
break;
}
}
return found;
}
private static void answerToTopic(Topic topic, String answer) throws PermissionsDeniedException {
postPage.getNewButton().click();
topicPage.getMainBodyArea().sendKeys(answer);
clickAnswerToTopicButton(topic);
}
/**
* Looks through several pages of the branch in order to find the topic with the specified id.
*
* @param numberOfPagesToCheck since the topic might not be on the first page (either someone simultaneously creates
* a lot of topics, or there are a lot of sticked topics), we have to iteration through
* this number of pages to search for the topic
* @param topicToFind a topic id to look for
* @return true if the specified topic was found
* @throws CouldNotOpenPageException if specified topic was not found
*/
private static boolean openTopicInCurrentBranch(int numberOfPagesToCheck, String topicToFind)
throws CouldNotOpenPageException {
boolean found;
while (!(found = findTopic(topicToFind))) {
if (!openNextPage(numberOfPagesToCheck)) break;
}
if (!found) {
LOGGER.info("No topic with title [{}] found", topicToFind);
throw new CouldNotOpenPageException(topicToFind);
}
return found;
}
private static boolean openNextPage(int pagesToCheck) {
int max = 0;
if (topicPage.getActiveTopicsButton().size() < 1) {
return false;
}
WebElement activeBtn = topicPage.getActiveTopicsButton().get(0);
int active = Integer.parseInt(activeBtn.getText().trim());
for (WebElement el : topicPage.getTopicsButtons()) {
if (Integer.parseInt(el.getText().trim()) > max)
max = Integer.parseInt(el.getText().trim());
}
if ((active < pagesToCheck) && (active < max)) {
for (WebElement elem : topicPage.getTopicsButtons()) {
if (Integer.parseInt(elem.getText().trim()) == (active + 1)) {
elem.click();
return true;
}
}
}
return false;
}
public static boolean senseToPageNext(Topic topic) {
WebElement bottomRowOfTopics = topicPage.getLastTopicLine();
System.out.println(bottomRowOfTopics.getText());
System.out.println(bottomRowOfTopics.findElement(By.className("sticky")).getText());
System.out.println("Topic date is " + topic.getModificationDate());
//if (bottomRowOfTopics.findElements(By.xpath("*/span[contains(@class,'sticky')]")).size()>0) return true;
String dateFromBottomRowOfTopics = bottomRowOfTopics.findElement(By.xpath("*/a[contains(@class,'date')]")).getText().trim();
return isTopicNewer(DateTime.now(), dateFromBottomRowOfTopics);
}
/**
* Sets state for checkbox element
*
* @param checkboxElement the checkbox web element
* @param state the state: true - checked, false - unchecked, null - the element is not used
*/
private static void setCheckboxState(WebElement checkboxElement, Boolean state) {
if (state == null) {
return;
}
if (state && !checkboxElement.isSelected()) {
checkboxElement.click();
} else if (!state && checkboxElement.isSelected()) {
checkboxElement.click();
}
}
/**
* Sets the end date in the poll.
*
* @param poll the poll.
*/
private static void setPollsEndDate(Poll poll) {
String date;
if ((date = dateToString(poll.getEndDate(), POLL_END_DATE_FORMAT)) != null) {
topicPage.getTopicsPollEndDateField().sendKeys(date);
}
}
/**
* Returns date in string type.
*
* @param date the date.
* @param format the format of date in string.
* @return the date in the string.
*/
private static void clickAnswerToTopicButton(Topic topic) throws PermissionsDeniedException {
try {
topicPage.getPostButton().click();
} catch (NoSuchElementException e) {
throw new PermissionsDeniedException("User does not have permissions to leave posts in branch "
+ topic.getBranch().getTitle());
}
}
private static void fillPollSpecificFields(Poll poll) {
if (poll != null) {
topicPage.getTopicPollTitleField().sendKeys(poll.getTitle());
WebElement optionsField = topicPage.getTopicPollItemsField();
for (String option : poll.getOptions()) {
optionsField.sendKeys(option + "\n");
}
setPollsEndDate(poll);
setCheckboxState(topicPage.getTopicsPollMultipleChecker(), poll.isMultipleAnswers());
}
}
private static void fillTopicFields(Topic topic) {
setCheckboxState(topicPage.getTopicSticked(), topic.getSticked());
setCheckboxState(topicPage.getTopicAnnouncement(), topic.getAnnouncement());
topicPage.getSubjectField().sendKeys(!topic.getTitle().equals("") ? topic.getTitle() : randomString(15));
topicPage.getMainBodyArea().sendKeys(topic.getFirstPost().getPostContent());
}
private static void clickCreateTopic() throws PermissionsDeniedException {
try {
topicPage.getNewButton().click();
} catch (NoSuchElementException e) {
throw new PermissionsDeniedException();
}
}
/**
* Returns date in string type.
*
* @param date the date.
* @param format the format of date in string.
* @return the date in the string.
*/
private static String dateToString(Date date, String format) {
if (date != null) {
return new SimpleDateFormat(format).format(date);
}
return null;
}
/**
* Create new topic
*
* @param topic
* the topic representation
* @throws PermissionsDeniedException
*/
}
|
delete commented code
|
jcommune-webdriver/src/main/java/org/jtalks/tests/jcommune/webdriver/action/Topics.java
|
delete commented code
|
<ide><path>commune-webdriver/src/main/java/org/jtalks/tests/jcommune/webdriver/action/Topics.java
<ide> return topic;
<ide> }
<ide>
<del> /**
<del> * Create new topic
<del> *
<del> * @param topic the topic representation
<del> * @throws PermissionsDeniedException
<del> */
<del> /*
<del> private static Topic createNewTopic(Topic topic) throws PermissionsDeniedException {
<del> Branches.openBranch(topic.getBranch().getTitle());
<del> clickCreateTopic();
<del> fillTopicFields(topic);
<del> fillPollSpecificFields(topic.getPoll());
<del> clickAnswerToTopicButton(topic);
<del> topic.setModificationDate(org.joda.time.DateTime.now().plusMinutes(1));
<del> return topic;
<del> }
<del>
<del>*/
<ide> public static void createCodeReview(Topic topic) throws PermissionsDeniedException, CouldNotOpenPageException {
<ide> if (topic.getBranch() == null) {
<ide> Branch branch = new Branch(branchPage.getBranchList().get(0).getText());
|
|
Java
|
apache-2.0
|
0b2da55acfd7142f40d7a8a10344ec2f4f6b8051
| 0 |
jonmcewen/camel,alvinkwekel/camel,pkletsko/camel,sverkera/camel,mgyongyosi/camel,CodeSmell/camel,rmarting/camel,cunningt/camel,davidkarlsen/camel,salikjan/camel,rmarting/camel,snurmine/camel,isavin/camel,anton-k11/camel,curso007/camel,jamesnetherton/camel,kevinearls/camel,Fabryprog/camel,pax95/camel,apache/camel,akhettar/camel,tdiesler/camel,cunningt/camel,DariusX/camel,gautric/camel,drsquidop/camel,pmoerenhout/camel,adessaigne/camel,pkletsko/camel,ullgren/camel,rmarting/camel,rmarting/camel,akhettar/camel,dmvolod/camel,snurmine/camel,gnodet/camel,punkhorn/camel-upstream,Fabryprog/camel,christophd/camel,nikhilvibhav/camel,pmoerenhout/camel,kevinearls/camel,christophd/camel,CodeSmell/camel,adessaigne/camel,nicolaferraro/camel,gnodet/camel,anton-k11/camel,tdiesler/camel,adessaigne/camel,objectiser/camel,drsquidop/camel,gautric/camel,zregvart/camel,alvinkwekel/camel,gnodet/camel,apache/camel,ullgren/camel,drsquidop/camel,jonmcewen/camel,isavin/camel,mgyongyosi/camel,objectiser/camel,objectiser/camel,mcollovati/camel,DariusX/camel,nikhilvibhav/camel,akhettar/camel,jonmcewen/camel,mcollovati/camel,onders86/camel,akhettar/camel,nicolaferraro/camel,anton-k11/camel,cunningt/camel,nikhilvibhav/camel,tdiesler/camel,Thopap/camel,Thopap/camel,nicolaferraro/camel,cunningt/camel,tadayosi/camel,Thopap/camel,snurmine/camel,salikjan/camel,pkletsko/camel,tadayosi/camel,punkhorn/camel-upstream,gautric/camel,gautric/camel,jamesnetherton/camel,snurmine/camel,anoordover/camel,DariusX/camel,punkhorn/camel-upstream,pax95/camel,DariusX/camel,apache/camel,apache/camel,jonmcewen/camel,isavin/camel,anoordover/camel,pkletsko/camel,onders86/camel,jamesnetherton/camel,isavin/camel,apache/camel,anton-k11/camel,objectiser/camel,mgyongyosi/camel,alvinkwekel/camel,pkletsko/camel,tadayosi/camel,mgyongyosi/camel,cunningt/camel,christophd/camel,onders86/camel,adessaigne/camel,cunningt/camel,drsquidop/camel,gnodet/camel,tdiesler/camel,pmoerenhout/camel,anoordover/camel,curso007/camel,dmvolod/camel,isavin/camel,davidkarlsen/camel,curso007/camel,dmvolod/camel,tadayosi/camel,sverkera/camel,drsquidop/camel,rmarting/camel,mcollovati/camel,christophd/camel,jamesnetherton/camel,dmvolod/camel,zregvart/camel,christophd/camel,tdiesler/camel,isavin/camel,mcollovati/camel,ullgren/camel,tdiesler/camel,CodeSmell/camel,christophd/camel,jamesnetherton/camel,pmoerenhout/camel,dmvolod/camel,curso007/camel,snurmine/camel,Fabryprog/camel,Fabryprog/camel,sverkera/camel,kevinearls/camel,onders86/camel,tadayosi/camel,Thopap/camel,drsquidop/camel,pax95/camel,sverkera/camel,gnodet/camel,adessaigne/camel,snurmine/camel,anoordover/camel,anton-k11/camel,nicolaferraro/camel,kevinearls/camel,pmoerenhout/camel,apache/camel,pax95/camel,gautric/camel,pax95/camel,kevinearls/camel,sverkera/camel,curso007/camel,pax95/camel,Thopap/camel,rmarting/camel,adessaigne/camel,davidkarlsen/camel,alvinkwekel/camel,zregvart/camel,zregvart/camel,jonmcewen/camel,kevinearls/camel,pmoerenhout/camel,pkletsko/camel,jonmcewen/camel,CodeSmell/camel,jamesnetherton/camel,mgyongyosi/camel,mgyongyosi/camel,anoordover/camel,curso007/camel,anton-k11/camel,davidkarlsen/camel,dmvolod/camel,onders86/camel,akhettar/camel,nikhilvibhav/camel,Thopap/camel,ullgren/camel,akhettar/camel,onders86/camel,sverkera/camel,tadayosi/camel,punkhorn/camel-upstream,gautric/camel,anoordover/camel
|
/**
* 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.camel.builder;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.Component;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.NoSuchEndpointException;
import org.apache.camel.NoSuchLanguageException;
import org.apache.camel.NoTypeConversionAvailableException;
import org.apache.camel.Producer;
import org.apache.camel.RuntimeExchangeException;
import org.apache.camel.component.bean.BeanInvocation;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.language.bean.BeanLanguage;
import org.apache.camel.language.simple.SimpleLanguage;
import org.apache.camel.model.language.MethodCallExpression;
import org.apache.camel.processor.DefaultExchangeFormatter;
import org.apache.camel.spi.ExchangeFormatter;
import org.apache.camel.spi.Language;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.spi.UnitOfWork;
import org.apache.camel.support.ExpressionAdapter;
import org.apache.camel.support.TokenPairExpressionIterator;
import org.apache.camel.support.TokenXMLExpressionIterator;
import org.apache.camel.support.XMLTokenExpressionIterator;
import org.apache.camel.util.CamelContextHelper;
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.GroupIterator;
import org.apache.camel.util.GroupTokenIterator;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.MessageHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.OgnlHelper;
import org.apache.camel.util.SkipIterator;
import org.apache.camel.util.StringHelper;
/**
* A helper class for working with <a href="http://camel.apache.org/expression.html">expressions</a>.
*
* @version
*/
public final class ExpressionBuilder {
private static final Pattern OFFSET_PATTERN = Pattern.compile("([+-])([^+-]+)");
/**
* Utility classes should not have a public constructor.
*/
private ExpressionBuilder() {
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentObjectsExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachmentObjects();
}
@Override
public String toString() {
return "attachmentObjects";
}
};
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentObjectValuesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachmentObjects().values();
}
@Override
public String toString() {
return "attachmentObjects";
}
};
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentsExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachments();
}
@Override
public String toString() {
return "attachments";
}
};
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentValuesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachments().values();
}
@Override
public String toString() {
return "attachments";
}
};
}
/**
* Returns an expression for the header value with the given name
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @return an expression object which will return the header value
*/
public static Expression headerExpression(final String headerName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = simpleExpression(headerName).evaluate(exchange, String.class);
Object header = exchange.getIn().getHeader(name);
if (header == null) {
// fall back on a property
header = exchange.getProperty(name);
}
return header;
}
@Override
public String toString() {
return "header(" + headerName + ")";
}
};
}
/**
* Returns an expression for the header value with the given name converted to the given type
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @param type the type to convert to
* @return an expression object which will return the header value
*/
public static <T> Expression headerExpression(final String headerName, final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = simpleExpression(headerName).evaluate(exchange, String.class);
Object header = exchange.getIn().getHeader(name, type);
if (header == null) {
// fall back on a property
header = exchange.getProperty(name, type);
}
return header;
}
@Override
public String toString() {
return "headerAs(" + headerName + ", " + type + ")";
}
};
}
/**
* Returns an expression for the header value with the given name converted to the given type
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @param typeName the type to convert to as a FQN class name
* @return an expression object which will return the header value
*/
public static Expression headerExpression(final String headerName, final String typeName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Class<?> type;
try {
String text = simpleExpression(typeName).evaluate(exchange, String.class);
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
String text = simpleExpression(headerName).evaluate(exchange, String.class);
Object header = exchange.getIn().getHeader(text, type);
if (header == null) {
// fall back on a property
header = exchange.getProperty(text, type);
}
return header;
}
@Override
public String toString() {
return "headerAs(" + headerName + ", " + typeName + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message header invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the header in a simple OGNL syntax
*/
public static Expression headersOgnlExpression(final String ognl) {
return new KeyedOgnlExpressionAdapter(ognl, "headerOgnl(" + ognl + ")",
new KeyedOgnlExpressionAdapter.KeyedEntityRetrievalStrategy() {
public Object getKeyedEntity(Exchange exchange, String key) {
String text = simpleExpression(key).evaluate(exchange, String.class);
return exchange.getIn().getHeader(text);
}
});
}
/**
* Returns an expression for the inbound message headers
*
* @return an expression object which will return the inbound headers
*/
public static Expression headersExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeaders();
}
@Override
public String toString() {
return "headers";
}
};
}
/**
* Returns an expression for the out header value with the given name
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @return an expression object which will return the header value
*/
public static Expression outHeaderExpression(final String headerName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (!exchange.hasOut()) {
return null;
}
String text = simpleExpression(headerName).evaluate(exchange, String.class);
Message out = exchange.getOut();
Object header = out.getHeader(text);
if (header == null) {
// let's try the exchange header
header = exchange.getProperty(text);
}
return header;
}
@Override
public String toString() {
return "outHeader(" + headerName + ")";
}
};
}
/**
* Returns an expression for the outbound message headers
*
* @return an expression object which will return the headers, will be <tt>null</tt> if the
* exchange is not out capable.
*/
public static Expression outHeadersExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// only get out headers if the MEP is out capable
if (ExchangeHelper.isOutCapable(exchange)) {
return exchange.getOut().getHeaders();
} else {
return null;
}
}
@Override
public String toString() {
return "outHeaders";
}
};
}
/**
* Returns an expression for the exchange pattern
*
* @see org.apache.camel.Exchange#getPattern()
* @return an expression object which will return the exchange pattern
*/
public static Expression exchangePatternExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getPattern();
}
@Override
public String toString() {
return "exchangePattern";
}
};
}
/**
* Returns an expression for an exception set on the exchange
*
* @see Exchange#getException()
* @return an expression object which will return the exception set on the exchange
*/
public static Expression exchangeExceptionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
return exception;
}
@Override
public String toString() {
return "exchangeException";
}
};
}
/**
* Returns an expression for an exception set on the exchange
* <p/>
* Is used to get the caused exception that typically have been wrapped in some sort
* of Camel wrapper exception
* @param type the exception type
* @see Exchange#getException(Class)
* @return an expression object which will return the exception set on the exchange
*/
public static Expression exchangeExceptionExpression(final Class<Exception> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException(type);
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
return ObjectHelper.getException(type, exception);
}
return exception;
}
@Override
public String toString() {
return "exchangeException[" + type + "]";
}
};
}
/**
* Returns the expression for the exchanges exception invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the body in a simple OGNL syntax
*/
public static Expression exchangeExceptionOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
if (exception == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(exception, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "exchangeExceptionOgnl(" + ognl + ")";
}
};
}
/**
* Returns an expression for the type converter
*
* @return an expression object which will return the type converter
*/
public static Expression typeConverterExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getTypeConverter();
}
@Override
public String toString() {
return "typeConverter";
}
};
}
/**
* Returns an expression for the {@link org.apache.camel.spi.Registry}
*
* @return an expression object which will return the registry
*/
public static Expression registryExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getRegistry();
}
@Override
public String toString() {
return "registry";
}
};
}
/**
* Returns an expression for lookup a bean in the {@link org.apache.camel.spi.Registry}
*
* @return an expression object which will return the bean
*/
public static Expression refExpression(final String ref) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(ref).evaluate(exchange, String.class);
return exchange.getContext().getRegistry().lookupByName(text);
}
@Override
public String toString() {
return "ref(" + ref + ")";
}
};
}
/**
* Returns an expression for the {@link org.apache.camel.CamelContext}
*
* @return an expression object which will return the camel context
*/
public static Expression camelContextExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext();
}
@Override
public String toString() {
return "camelContext";
}
};
}
/**
* Returns an expression for the {@link org.apache.camel.CamelContext} name
*
* @return an expression object which will return the camel context name
*/
public static Expression camelContextNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getName();
}
@Override
public String toString() {
return "camelContextName";
}
};
}
/**
* Returns an expression for an exception message set on the exchange
*
* @see <tt>Exchange.getException().getMessage()</tt>
* @return an expression object which will return the exception message set on the exchange
*/
public static Expression exchangeExceptionMessageExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
return exception != null ? exception.getMessage() : null;
}
@Override
public String toString() {
return "exchangeExceptionMessage";
}
};
}
/**
* Returns an expression for an exception stacktrace set on the exchange
*
* @return an expression object which will return the exception stacktrace set on the exchange
*/
public static Expression exchangeExceptionStackTraceExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
if (exception != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
IOHelper.close(pw, sw);
return sw.toString();
} else {
return null;
}
}
@Override
public String toString() {
return "exchangeExceptionStackTrace";
}
};
}
/**
* Returns an expression for the property value of exchange with the given name
*
* @param propertyName the name of the property the expression will return
* @return an expression object which will return the property value
* @deprecated use {@link #exchangePropertyExpression(String)} instead
*/
@Deprecated
public static Expression propertyExpression(final String propertyName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
return exchange.getProperty(text);
}
@Override
public String toString() {
return "exchangeProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for the property value of exchange with the given name
*
* @param propertyName the name of the property the expression will return
* @return an expression object which will return the property value
*/
public static Expression exchangePropertyExpression(final String propertyName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
return exchange.getProperty(text);
}
@Override
public String toString() {
return "exchangeProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for the property value of exchange with the given name invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the property in a simple OGNL syntax
*/
public static Expression propertyOgnlExpression(final String ognl) {
return new KeyedOgnlExpressionAdapter(ognl, "propertyOgnl(" + ognl + ")",
new KeyedOgnlExpressionAdapter.KeyedEntityRetrievalStrategy() {
public Object getKeyedEntity(Exchange exchange, String key) {
String text = simpleExpression(key).evaluate(exchange, String.class);
return exchange.getProperty(text);
}
});
}
/**
* Returns an expression for the properties of exchange
*
* @return an expression object which will return the properties
* @deprecated use {@link #exchangeExceptionExpression()} instead
*/
@Deprecated
public static Expression propertiesExpression() {
return exchangeExceptionExpression();
}
/**
* Returns an expression for the exchange properties of exchange
*
* @return an expression object which will return the exchange properties
*/
public static Expression exchangePropertiesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getProperties();
}
@Override
public String toString() {
return "exchangeProperties";
}
};
}
/**
* Returns an expression for the properties of the camel context
*
* @return an expression object which will return the properties
*/
public static Expression camelContextPropertiesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getGlobalOptions();
}
@Override
public String toString() {
return "camelContextProperties";
}
};
}
/**
* Returns an expression for the property value of the camel context with the given name
*
* @param propertyName the name of the property the expression will return
* @return an expression object which will return the property value
*/
public static Expression camelContextPropertyExpression(final String propertyName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
return exchange.getContext().getGlobalOption(text);
}
@Override
public String toString() {
return "camelContextProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for a system property value with the given name
*
* @param propertyName the name of the system property the expression will return
* @return an expression object which will return the system property value
*/
public static Expression systemPropertyExpression(final String propertyName) {
return systemPropertyExpression(propertyName, null);
}
/**
* Returns an expression for a system property value with the given name
*
* @param propertyName the name of the system property the expression will return
* @param defaultValue default value to return if no system property exists
* @return an expression object which will return the system property value
*/
public static Expression systemPropertyExpression(final String propertyName,
final String defaultValue) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
String text2 = simpleExpression(defaultValue).evaluate(exchange, String.class);
return System.getProperty(text, text2);
}
@Override
public String toString() {
return "systemProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for a system environment value with the given name
*
* @param propertyName the name of the system environment the expression will return
* @return an expression object which will return the system property value
*/
public static Expression systemEnvironmentExpression(final String propertyName) {
return systemEnvironmentExpression(propertyName, null);
}
/**
* Returns an expression for a system environment value with the given name
*
* @param propertyName the name of the system environment the expression will return
* @param defaultValue default value to return if no system environment exists
* @return an expression object which will return the system environment value
*/
public static Expression systemEnvironmentExpression(final String propertyName,
final String defaultValue) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
String answer = System.getenv(text);
if (answer == null) {
String text2 = simpleExpression(defaultValue).evaluate(exchange, String.class);
answer = text2;
}
return answer;
}
@Override
public String toString() {
return "systemEnvironment(" + propertyName + ")";
}
};
}
/**
* Returns an expression for the constant value
*
* @param value the value the expression will return
* @return an expression object which will return the constant value
*/
public static Expression constantExpression(final Object value) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return value;
}
@Override
public String toString() {
return "" + value;
}
};
}
/**
* Returns an expression for evaluating the expression/predicate using the given language
*
* @param expression the expression or predicate
* @return an expression object which will evaluate the expression/predicate using the given language
*/
public static Expression languageExpression(final String language, final String expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Language lan = exchange.getContext().resolveLanguage(language);
if (lan != null) {
return lan.createExpression(expression).evaluate(exchange, Object.class);
} else {
throw new NoSuchLanguageException(language);
}
}
@Override
public boolean matches(Exchange exchange) {
Language lan = exchange.getContext().resolveLanguage(language);
if (lan != null) {
return lan.createPredicate(expression).matches(exchange);
} else {
throw new NoSuchLanguageException(language);
}
}
@Override
public String toString() {
return "language[" + language + ":" + expression + "]";
}
};
}
/**
* Returns an expression for a type value
*
* @param name the type name
* @return an expression object which will return the type value
*/
public static Expression typeExpression(final String name) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// it may refer to a class type
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type = exchange.getContext().getClassResolver().resolveClass(text);
if (type != null) {
return type;
}
int pos = text.lastIndexOf(".");
if (pos > 0) {
String before = text.substring(0, pos);
String after = text.substring(pos + 1);
type = exchange.getContext().getClassResolver().resolveClass(before);
if (type != null) {
return ObjectHelper.lookupConstantFieldValue(type, after);
}
}
throw ObjectHelper.wrapCamelExecutionException(exchange, new ClassNotFoundException("Cannot find type " + text));
}
@Override
public String toString() {
return "type:" + name;
}
};
}
/**
* Returns an expression that caches the evaluation of another expression
* and returns the cached value, to avoid re-evaluating the expression.
*
* @param expression the target expression to cache
* @return the cached value
*/
public static Expression cacheExpression(final Expression expression) {
return new ExpressionAdapter() {
private final AtomicReference<Object> cache = new AtomicReference<Object>();
public Object evaluate(Exchange exchange) {
Object answer = cache.get();
if (answer == null) {
answer = expression.evaluate(exchange, Object.class);
cache.set(answer);
}
return answer;
}
@Override
public String toString() {
return expression.toString();
}
};
}
/**
* Returns the expression for the exchanges inbound message body
*/
public static Expression bodyExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getBody();
}
@Override
public String toString() {
return "body";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body
*/
public static Expression bodyExpression(final Function<Object, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody()
);
}
@Override
public String toString() {
return "bodyExpression";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body and headers
*/
public static Expression bodyExpression(final BiFunction<Object, Map<String, Object>, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody(),
exchange.getIn().getHeaders()
);
}
@Override
public String toString() {
return "bodyExpression";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body converted to a desired type
*/
public static <T> Expression bodyExpression(final Class<T> bodyType, final Function<T, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody(bodyType)
);
}
@Override
public String toString() {
return "bodyExpression (" + bodyType + ")";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body converted to a desired type and headers
*/
public static <T> Expression bodyExpression(final Class<T> bodyType, final BiFunction<T, Map<String, Object>, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody(bodyType),
exchange.getIn().getHeaders()
);
}
@Override
public String toString() {
return "bodyExpression (" + bodyType + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message body invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the body in a simple OGNL syntax
*/
public static Expression bodyOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object body = exchange.getIn().getBody();
if (body == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(body, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "bodyOgnl(" + ognl + ")";
}
};
}
/**
* Returns the expression for invoking a method (support OGNL syntax) on the given expression
*
* @param exp the expression to evaluate and invoke the method on its result
* @param ognl methods to invoke on the evaluated expression in a simple OGNL syntax
*/
public static Expression ognlExpression(final Expression exp, final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object value = exp.evaluate(exchange, Object.class);
if (value == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(value, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "ognl(" + exp + ", " + ognl + ")";
}
};
}
/**
* Returns the expression for the exchanges camelContext invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the context in a simple OGNL syntax
*/
public static Expression camelContextOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
CamelContext context = exchange.getContext();
if (context == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(context, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "camelContextOgnl(" + ognl + ")";
}
};
}
/**
* Returns the expression for the exchange invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the exchange in a simple OGNL syntax
*/
public static Expression exchangeOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(exchange, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "exchangeOgnl(" + ognl + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*/
public static <T> Expression bodyExpression(final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getBody(type);
}
@Override
public String toString() {
return "bodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*/
public static Expression bodyExpression(final String name) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
return exchange.getIn().getBody(type);
}
@Override
public String toString() {
return "bodyAs[" + name + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type and invoking methods on the converted body defined in a simple OGNL notation
*/
public static Expression bodyOgnlExpression(final String name, final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
Object body = exchange.getIn().getBody(type);
if (body != null) {
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
MethodCallExpression call = new MethodCallExpression(exchange, ognl);
// set the instance to use
call.setInstance(body);
return call.evaluate(exchange);
} else {
return null;
}
}
@Override
public String toString() {
return "bodyOgnlAs[" + name + "](" + ognl + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*/
public static Expression mandatoryBodyExpression(final String name) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
try {
return exchange.getIn().getMandatoryBody(type);
} catch (InvalidPayloadException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
}
@Override
public String toString() {
return "mandatoryBodyAs[" + name + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type and invoking methods on the converted body defined in a simple OGNL notation
*/
public static Expression mandatoryBodyOgnlExpression(final String name, final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
Object body;
try {
body = exchange.getIn().getMandatoryBody(type);
} catch (InvalidPayloadException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
MethodCallExpression call = new MethodCallExpression(exchange, ognl);
// set the instance to use
call.setInstance(body);
return call.evaluate(exchange);
}
@Override
public String toString() {
return "mandatoryBodyAs[" + name + "](" + ognl + ")";
}
};
}
/**
* Returns the expression for the current thread name
*/
public static Expression threadNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return Thread.currentThread().getName();
}
@Override
public String toString() {
return "threadName";
}
};
}
/**
* Returns the expression for the {@code null} value
*/
public static Expression nullExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return null;
}
@Override
public String toString() {
return "null";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type.
* <p/>
* Does <b>not</b> allow null bodies.
*/
public static <T> Expression mandatoryBodyExpression(final Class<T> type) {
return mandatoryBodyExpression(type, false);
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*
* @param type the type
* @param nullBodyAllowed whether null bodies is allowed and if so a null is returned,
* otherwise an exception is thrown
*/
public static <T> Expression mandatoryBodyExpression(final Class<T> type, final boolean nullBodyAllowed) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (nullBodyAllowed) {
if (exchange.getIn().getBody() == null) {
return null;
}
// if its a bean invocation then if it has no arguments then it should be threaded as null body allowed
if (exchange.getIn().getBody() instanceof BeanInvocation) {
// BeanInvocation would be stored directly as the message body
// do not force any type conversion attempts as it would just be unnecessary and cost a bit performance
// so a regular instanceof check is sufficient
BeanInvocation bi = (BeanInvocation) exchange.getIn().getBody();
if (bi.getArgs() == null || bi.getArgs().length == 0 || bi.getArgs()[0] == null) {
return null;
}
}
}
try {
return exchange.getIn().getMandatoryBody(type);
} catch (InvalidPayloadException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
}
@Override
public String toString() {
return "mandatoryBodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body type
*/
public static Expression bodyTypeExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getBody().getClass();
}
@Override
public String toString() {
return "bodyType";
}
};
}
/**
* Returns the expression for the out messages body
*/
public static Expression outBodyExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (exchange.hasOut()) {
return exchange.getOut().getBody();
} else {
return null;
}
}
@Override
public String toString() {
return "outBody";
}
};
}
/**
* Returns the expression for the exchanges outbound message body converted
* to the given type
*/
public static <T> Expression outBodyExpression(final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (exchange.hasOut()) {
return exchange.getOut().getBody(type);
} else {
return null;
}
}
@Override
public String toString() {
return "outBodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the fault messages body
*/
public static Expression faultBodyExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
return msg.isFault() ? msg.getBody() : null;
}
@Override
public String toString() {
return "faultBody";
}
};
}
/**
* Returns the expression for the exchanges fault message body converted
* to the given type
*/
public static <T> Expression faultBodyExpression(final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
return msg.isFault() ? msg.getBody(type) : null;
}
@Override
public String toString() {
return "faultBodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the exchange
*/
public static Expression exchangeExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange;
}
@Override
public String toString() {
return "exchange";
}
};
}
/**
* Returns a functional expression for the exchange
*/
public static Expression exchangeExpression(final Function<Exchange, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(exchange);
}
@Override
public String toString() {
return "exchangeExpression";
}
};
}
/**
* Returns the expression for the IN message
*/
public static Expression messageExpression() {
return inMessageExpression();
}
/**
* Returns a functional expression for the IN message
*/
public static Expression messageExpression(final Function<Message, Object> function) {
return inMessageExpression(function);
}
/**
* Returns the expression for the IN message
*/
public static Expression inMessageExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn();
}
@Override
public String toString() {
return "inMessage";
}
};
}
/**
* Returns a functional expression for the IN message
*/
public static Expression inMessageExpression(final Function<Message, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(exchange.getIn());
}
@Override
public String toString() {
return "inMessageExpression";
}
};
}
/**
* Returns the expression for the OUT message
*/
public static Expression outMessageExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getOut();
}
@Override
public String toString() {
return "outMessage";
}
};
}
/**
* Returns a functional expression for the OUT message
*/
public static Expression outMessageExpression(final Function<Message, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(exchange.getOut());
}
@Override
public String toString() {
return "outMessageExpression";
}
};
}
/**
* Returns an expression which converts the given expression to the given type
*/
public static Expression convertToExpression(final Expression expression, final Class<?> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (type != null) {
return expression.evaluate(exchange, type);
} else {
return expression;
}
}
@Override
public String toString() {
return "" + expression;
}
};
}
/**
* Returns an expression which converts the given expression to the given type the type
* expression is evaluated to
*/
public static Expression convertToExpression(final Expression expression, final Expression type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object result = type.evaluate(exchange, Object.class);
if (result != null) {
return expression.evaluate(exchange, result.getClass());
} else {
return expression;
}
}
@Override
public String toString() {
return "" + expression;
}
};
}
/**
* Returns a tokenize expression which will tokenize the string with the
* given token
*/
public static Expression tokenizeExpression(final Expression expression,
final String token) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(token).evaluate(exchange, String.class);
Object value = expression.evaluate(exchange, Object.class);
Scanner scanner = ObjectHelper.getScanner(exchange, value);
scanner.useDelimiter(text);
return scanner;
}
@Override
public String toString() {
return "tokenize(" + expression + ", " + token + ")";
}
};
}
/**
* Returns an expression that skips the first element
*/
public static Expression skipFirstExpression(final Expression expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object value = expression.evaluate(exchange, Object.class);
Iterator it = exchange.getContext().getTypeConverter().tryConvertTo(Iterator.class, exchange, value);
if (it != null) {
// skip first
it.next();
return it;
} else {
return value;
}
}
@Override
public String toString() {
return "skipFirst(" + expression + ")";
}
};
}
/**
* Returns an {@link TokenPairExpressionIterator} expression
*/
public static Expression tokenizePairExpression(String startToken, String endToken, boolean includeTokens) {
return new TokenPairExpressionIterator(startToken, endToken, includeTokens);
}
/**
* Returns an {@link TokenXMLExpressionIterator} expression
*/
public static Expression tokenizeXMLExpression(String tagName, String inheritNamespaceTagName) {
ObjectHelper.notEmpty(tagName, "tagName");
return new TokenXMLExpressionIterator(tagName, inheritNamespaceTagName);
}
public static Expression tokenizeXMLAwareExpression(String path, char mode) {
ObjectHelper.notEmpty(path, "path");
return new XMLTokenExpressionIterator(path, mode);
}
public static Expression tokenizeXMLAwareExpression(String path, char mode, int group) {
ObjectHelper.notEmpty(path, "path");
return new XMLTokenExpressionIterator(path, mode, group);
}
/**
* Returns a tokenize expression which will tokenize the string with the
* given regex
*/
public static Expression regexTokenizeExpression(final Expression expression,
final String regexTokenizer) {
final Pattern pattern = Pattern.compile(regexTokenizer);
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object value = expression.evaluate(exchange, Object.class);
Scanner scanner = ObjectHelper.getScanner(exchange, value);
scanner.useDelimiter(pattern);
return scanner;
}
@Override
public String toString() {
return "regexTokenize(" + expression + ", " + pattern.pattern() + ")";
}
};
}
public static Expression groupXmlIteratorExpression(final Expression expression, final String group) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// evaluate expression as iterator
Iterator<?> it = expression.evaluate(exchange, Iterator.class);
ObjectHelper.notNull(it, "expression: " + expression + " evaluated on " + exchange + " must return an java.util.Iterator");
// must use GroupTokenIterator in xml mode as we want to concat the xml parts into a single message
// the group can be a simple expression so evaluate it as a number
Integer parts = exchange.getContext().resolveLanguage("simple").createExpression(group).evaluate(exchange, Integer.class);
if (parts == null) {
throw new RuntimeExchangeException("Group evaluated as null, must be evaluated as a positive Integer value from expression: " + group, exchange);
} else if (parts <= 0) {
throw new RuntimeExchangeException("Group must be a positive number, was: " + parts, exchange);
}
return new GroupTokenIterator(exchange, it, null, parts, false);
}
@Override
public String toString() {
return "group " + expression + " " + group + " times";
}
};
}
public static Expression groupIteratorExpression(final Expression expression, final String token, final String group, final boolean skipFirst) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// evaluate expression as iterator
Iterator<?> it = expression.evaluate(exchange, Iterator.class);
ObjectHelper.notNull(it, "expression: " + expression + " evaluated on " + exchange + " must return an java.util.Iterator");
// the group can be a simple expression so evaluate it as a number
Integer parts = exchange.getContext().resolveLanguage("simple").createExpression(group).evaluate(exchange, Integer.class);
if (parts == null) {
throw new RuntimeExchangeException("Group evaluated as null, must be evaluated as a positive Integer value from expression: " + group, exchange);
} else if (parts <= 0) {
throw new RuntimeExchangeException("Group must be a positive number, was: " + parts, exchange);
}
if (token != null) {
return new GroupTokenIterator(exchange, it, token, parts, skipFirst);
} else {
return new GroupIterator(exchange, it, parts, skipFirst);
}
}
@Override
public String toString() {
return "group " + expression + " " + group + " times";
}
};
}
public static Expression skipIteratorExpression(final Expression expression, final int skip) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// evaluate expression as iterator
Iterator<?> it = expression.evaluate(exchange, Iterator.class);
ObjectHelper.notNull(it, "expression: " + expression + " evaluated on " + exchange + " must return an java.util.Iterator");
return new SkipIterator(exchange, it, skip);
}
@Override
public String toString() {
return "skip " + expression + " " + skip + " times";
}
};
}
/**
* Returns a sort expression which will sort the expression with the given comparator.
* <p/>
* The expression is evaluated as a {@link List} object to allow sorting.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static Expression sortExpression(final Expression expression, final Comparator comparator) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
List<?> list = expression.evaluate(exchange, List.class);
list.sort(comparator);
return list;
}
@Override
public String toString() {
return "sort(" + expression + " by: " + comparator + ")";
}
};
}
/**
* Transforms the expression into a String then performs the regex
* replaceAll to transform the String and return the result
*/
public static Expression regexReplaceAll(final Expression expression,
final String regex, final String replacement) {
final Pattern pattern = Pattern.compile(regex);
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = expression.evaluate(exchange, String.class);
if (text == null) {
return null;
}
return pattern.matcher(text).replaceAll(replacement);
}
@Override
public String toString() {
return "regexReplaceAll(" + expression + ", " + pattern.pattern() + ")";
}
};
}
/**
* Transforms the expression into a String then performs the regex
* replaceAll to transform the String and return the result
*/
public static Expression regexReplaceAll(final Expression expression,
final String regex, final Expression replacementExpression) {
final Pattern pattern = Pattern.compile(regex);
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = expression.evaluate(exchange, String.class);
String replacement = replacementExpression.evaluate(exchange, String.class);
if (text == null || replacement == null) {
return null;
}
return pattern.matcher(text).replaceAll(replacement);
}
@Override
public String toString() {
return "regexReplaceAll(" + expression + ", " + pattern.pattern() + ")";
}
};
}
/**
* Appends the String evaluations of the two expressions together
*/
public static Expression append(final Expression left, final Expression right) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return left.evaluate(exchange, String.class) + right.evaluate(exchange, String.class);
}
@Override
public String toString() {
return "append(" + left + ", " + right + ")";
}
};
}
/**
* Prepends the String evaluations of the two expressions together
*/
public static Expression prepend(final Expression left, final Expression right) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return right.evaluate(exchange, String.class) + left.evaluate(exchange, String.class);
}
@Override
public String toString() {
return "prepend(" + left + ", " + right + ")";
}
};
}
/**
* Returns an expression which returns the string concatenation value of the various
* expressions
*
* @param expressions the expression to be concatenated dynamically
* @return an expression which when evaluated will return the concatenated values
*/
public static Expression concatExpression(final Collection<Expression> expressions) {
return concatExpression(expressions, null);
}
/**
* Returns an expression which returns the string concatenation value of the various
* expressions
*
* @param expressions the expression to be concatenated dynamically
* @param desription the text description of the expression
* @return an expression which when evaluated will return the concatenated values
*/
public static Expression concatExpression(final Collection<Expression> expressions, final String desription) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
StringBuilder buffer = new StringBuilder();
for (Expression expression : expressions) {
String text = expression.evaluate(exchange, String.class);
if (text != null) {
buffer.append(text);
}
}
return buffer.toString();
}
@Override
public String toString() {
if (desription != null) {
return desription;
} else {
return "concat" + expressions;
}
}
};
}
/**
* Returns an Expression for the inbound message id
*/
public static Expression messageIdExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getMessageId();
}
@Override
public String toString() {
return "messageId";
}
};
}
/**
* Returns an Expression for the exchange id
*/
public static Expression exchangeIdExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getExchangeId();
}
@Override
public String toString() {
return "exchangeId";
}
};
}
/**
* Returns an Expression for the route id
*/
public static Expression routeIdExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String answer = null;
UnitOfWork uow = exchange.getUnitOfWork();
RouteContext rc = uow != null ? uow.getRouteContext() : null;
if (rc != null) {
answer = rc.getRoute().getId();
}
if (answer == null) {
// fallback and get from route id on the exchange
answer = exchange.getFromRouteId();
}
return answer;
}
@Override
public String toString() {
return "routeId";
}
};
}
public static Expression dateExpression(final String command) {
return dateExpression(command, null, null);
}
public static Expression dateExpression(final String command, final String pattern) {
return dateExpression(command, null, pattern);
}
public static Expression dateExpression(final String commandWithOffsets, final String timezone, final String pattern) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// Capture optional time offsets
String command = commandWithOffsets.split("[+-]", 2)[0].trim();
List<Long> offsets = new ArrayList<>();
Matcher offsetMatcher = OFFSET_PATTERN.matcher(commandWithOffsets);
while (offsetMatcher.find()) {
try {
long value = exchange.getContext().getTypeConverter().mandatoryConvertTo(long.class, exchange, offsetMatcher.group(2).trim());
offsets.add(offsetMatcher.group(1).equals("+") ? value : -value);
} catch (NoTypeConversionAvailableException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
}
Date date;
if ("now".equals(command)) {
date = new Date();
} else if (command.startsWith("header.") || command.startsWith("in.header.")) {
String key = command.substring(command.lastIndexOf('.') + 1);
date = exchange.getIn().getHeader(key, Date.class);
if (date == null) {
throw new IllegalArgumentException("Cannot find java.util.Date object at command: " + command);
}
} else if (command.startsWith("out.header.")) {
String key = command.substring(command.lastIndexOf('.') + 1);
date = exchange.getOut().getHeader(key, Date.class);
if (date == null) {
throw new IllegalArgumentException("Cannot find java.util.Date object at command: " + command);
}
} else if ("file".equals(command)) {
Long num = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Long.class);
if (num != null && num > 0) {
date = new Date(num);
} else {
date = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Date.class);
if (date == null) {
throw new IllegalArgumentException("Cannot find " + Exchange.FILE_LAST_MODIFIED + " header at command: " + command);
}
}
} else {
throw new IllegalArgumentException("Command not supported for dateExpression: " + command);
}
// Apply offsets
long dateAsLong = date.getTime();
for (long offset : offsets) {
dateAsLong += offset;
}
date = new Date(dateAsLong);
if (pattern != null && !pattern.isEmpty()) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
if (timezone != null && !timezone.isEmpty()) {
df.setTimeZone(TimeZone.getTimeZone(timezone));
}
return df.format(date);
} else {
return date;
}
}
@Override
public String toString() {
return "date(" + commandWithOffsets + ":" + pattern + ":" + timezone + ")";
}
};
}
public static Expression simpleExpression(final String expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (SimpleLanguage.hasSimpleFunction(expression)) {
// resolve language using context to have a clear separation of packages
// must call evaluate to return the nested language evaluate when evaluating
// stacked expressions
Language language = exchange.getContext().resolveLanguage("simple");
return language.createExpression(expression).evaluate(exchange, Object.class);
} else {
return expression;
}
}
@Override
public String toString() {
return "simple(" + expression + ")";
}
};
}
public static Expression beanExpression(final String expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// bean is able to evaluate method name if it contains nested functions
// so we should not eager evaluate expression as a string
// resolve language using context to have a clear separation of packages
// must call evaluate to return the nested language evaluate when evaluating
// stacked expressions
Language language = exchange.getContext().resolveLanguage("bean");
return language.createExpression(expression).evaluate(exchange, Object.class);
}
@Override
public String toString() {
return "bean(" + expression + ")";
}
};
}
public static Expression beanExpression(final Class<?> beanType, final String methodName) {
return BeanLanguage.bean(beanType, methodName);
}
public static Expression beanExpression(final Object bean, final String methodName) {
return BeanLanguage.bean(bean, methodName);
}
public static Expression beanExpression(final String beanRef, final String methodName) {
String expression = methodName != null ? beanRef + "." + methodName : beanRef;
return beanExpression(expression);
}
/**
* Returns an expression processing the exchange to the given endpoint uri
*
* @param uri endpoint uri to send the exchange to
* @return an expression object which will return the OUT body
*/
public static Expression toExpression(final String uri) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(uri).evaluate(exchange, String.class);
Endpoint endpoint = exchange.getContext().getEndpoint(text);
if (endpoint == null) {
throw new NoSuchEndpointException(text);
}
Producer producer;
try {
producer = endpoint.createProducer();
producer.start();
producer.process(exchange);
producer.stop();
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
// return the OUT body, but check for exchange pattern
if (ExchangeHelper.isOutCapable(exchange)) {
return exchange.getOut().getBody();
} else {
return exchange.getIn().getBody();
}
}
@Override
public String toString() {
return "to(" + uri + ")";
}
};
}
public static Expression fileNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
}
@Override
public String toString() {
return "file:name";
}
};
}
public static Expression fileOnlyNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String answer = exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY, String.class);
if (answer == null) {
answer = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
answer = FileUtil.stripPath(answer);
}
return answer;
}
@Override
public String toString() {
return "file:onlyname";
}
};
}
public static Expression fileNameNoExtensionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.stripExt(name);
}
@Override
public String toString() {
return "file:name.noext";
}
};
}
public static Expression fileNameNoExtensionSingleExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.stripExt(name, true);
}
@Override
public String toString() {
return "file:name.noext.single";
}
};
}
public static Expression fileOnlyNameNoExtensionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = fileOnlyNameExpression().evaluate(exchange, String.class);
return FileUtil.stripExt(name);
}
@Override
public String toString() {
return "file:onlyname.noext";
}
};
}
public static Expression fileOnlyNameNoExtensionSingleExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = fileOnlyNameExpression().evaluate(exchange, String.class);
return FileUtil.stripExt(name, true);
}
@Override
public String toString() {
return "file:onlyname.noext.single";
}
};
}
public static Expression fileExtensionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.onlyExt(name);
}
@Override
public String toString() {
return "file:ext";
}
};
}
public static Expression fileExtensionSingleExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.onlyExt(name, true);
}
@Override
public String toString() {
return "file:ext.single";
}
};
}
public static Expression fileParentExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFileParent", String.class);
}
@Override
public String toString() {
return "file:parent";
}
};
}
public static Expression filePathExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFilePath", String.class);
}
@Override
public String toString() {
return "file:path";
}
};
}
public static Expression fileAbsolutePathExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFileAbsolutePath", String.class);
}
@Override
public String toString() {
return "file:absolute.path";
}
};
}
public static Expression fileAbsoluteExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFileAbsolute", Boolean.class);
}
@Override
public String toString() {
return "file:absolute";
}
};
}
public static Expression fileSizeExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader(Exchange.FILE_LENGTH, Long.class);
}
@Override
public String toString() {
return "file:length";
}
};
}
public static Expression fileLastModifiedExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Long.class);
}
@Override
public String toString() {
return "file:modified";
}
};
}
/**
* Returns Simple expression or fallback to Constant expression if expression str is not Simple expression.
*/
public static Expression parseSimpleOrFallbackToConstantExpression(String str, CamelContext camelContext) {
if (StringHelper.hasStartToken(str, "simple")) {
return camelContext.resolveLanguage("simple").createExpression(str);
}
return constantExpression(str);
}
public static Expression propertiesComponentExpression(final String key, final String locations, final String defaultValue) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(key).evaluate(exchange, String.class);
String text2 = simpleExpression(locations).evaluate(exchange, String.class);
try {
if (text2 != null) {
// the properties component is optional as we got locations
// getComponent will create a new component if none already exists
Component component = exchange.getContext().getComponent("properties");
PropertiesComponent pc = exchange.getContext().getTypeConverter()
.mandatoryConvertTo(PropertiesComponent.class, component);
// enclose key with {{ }} to force parsing
String[] paths = text2.split(",");
return pc.parseUri(pc.getPrefixToken() + text + pc.getSuffixToken(), paths);
} else {
// the properties component is mandatory if no locations provided
Component component = exchange.getContext().hasComponent("properties");
if (component == null) {
throw new IllegalArgumentException("PropertiesComponent with name properties must be defined"
+ " in CamelContext to support property placeholders in expressions");
}
PropertiesComponent pc = exchange.getContext().getTypeConverter()
.mandatoryConvertTo(PropertiesComponent.class, component);
// enclose key with {{ }} to force parsing
return pc.parseUri(pc.getPrefixToken() + text + pc.getSuffixToken());
}
} catch (Exception e) {
// property with key not found, use default value if provided
if (defaultValue != null) {
return defaultValue;
}
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
@Override
public String toString() {
return "properties(" + key + ")";
}
};
}
/**
* Returns a random number between 0 and max (exclusive)
*/
public static Expression randomExpression(final int max) {
return randomExpression(0, max);
}
/**
* Returns a random number between min and max (exclusive)
*/
public static Expression randomExpression(final int min, final int max) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Random random = new Random();
int randomNum = random.nextInt(max - min) + min;
return randomNum;
}
@Override
public String toString() {
return "random(" + min + "," + max + ")";
}
};
}
/**
* Returns a random number between min and max (exclusive)
*/
public static Expression randomExpression(final String min, final String max) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
int num1 = simpleExpression(min).evaluate(exchange, Integer.class);
int num2 = simpleExpression(max).evaluate(exchange, Integer.class);
Random random = new Random();
int randomNum = random.nextInt(num2 - num1) + num1;
return randomNum;
}
@Override
public String toString() {
return "random(" + min + "," + max + ")";
}
};
}
/**
* Returns an iterator to skip (iterate) the given expression
*/
public static Expression skipExpression(final String expression, final int number) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// use simple language
Expression exp = exchange.getContext().resolveLanguage("simple").createExpression(expression);
return ExpressionBuilder.skipIteratorExpression(exp, number).evaluate(exchange, Object.class);
}
@Override
public String toString() {
return "skip(" + expression + "," + number + ")";
}
};
}
/**
* Returns an iterator to collate (iterate) the given expression
*/
public static Expression collateExpression(final String expression, final int group) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// use simple language
Expression exp = exchange.getContext().resolveLanguage("simple").createExpression(expression);
return ExpressionBuilder.groupIteratorExpression(exp, null, "" + group, false).evaluate(exchange, Object.class);
}
@Override
public String toString() {
return "collate(" + expression + "," + group + ")";
}
};
}
/**
* Returns the message history (including exchange details or not)
*/
public static Expression messageHistoryExpression(final boolean detailed) {
return new ExpressionAdapter() {
private ExchangeFormatter formatter;
public Object evaluate(Exchange exchange) {
ExchangeFormatter ef = null;
if (detailed) {
// use the exchange formatter to log exchange details
ef = getOrCreateExchangeFormatter(exchange.getContext());
}
return MessageHelper.dumpMessageHistoryStacktrace(exchange, ef, false);
}
private ExchangeFormatter getOrCreateExchangeFormatter(CamelContext camelContext) {
if (formatter == null) {
Set<ExchangeFormatter> formatters = camelContext.getRegistry().findByType(ExchangeFormatter.class);
if (formatters != null && formatters.size() == 1) {
formatter = formatters.iterator().next();
} else {
// setup exchange formatter to be used for message history dump
DefaultExchangeFormatter def = new DefaultExchangeFormatter();
def.setShowExchangeId(true);
def.setMultiline(true);
def.setShowHeaders(true);
def.setStyle(DefaultExchangeFormatter.OutputStyle.Fixed);
try {
Integer maxChars = CamelContextHelper.parseInteger(camelContext, camelContext.getGlobalOption(Exchange.LOG_DEBUG_BODY_MAX_CHARS));
if (maxChars != null) {
def.setMaxChars(maxChars);
}
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
formatter = def;
}
}
return formatter;
}
@Override
public String toString() {
return "messageHistory(" + detailed + ")";
}
};
}
/**
* Expression adapter for OGNL expression from Message Header or Exchange property
*/
private static class KeyedOgnlExpressionAdapter extends ExpressionAdapter {
private final String ognl;
private final String toStringValue;
private final KeyedEntityRetrievalStrategy keyedEntityRetrievalStrategy;
KeyedOgnlExpressionAdapter(String ognl, String toStringValue,
KeyedEntityRetrievalStrategy keyedEntityRetrievalStrategy) {
this.ognl = ognl;
this.toStringValue = toStringValue;
this.keyedEntityRetrievalStrategy = keyedEntityRetrievalStrategy;
}
public Object evaluate(Exchange exchange) {
// try with full name first
Object property = keyedEntityRetrievalStrategy.getKeyedEntity(exchange, ognl);
if (property != null) {
return property;
}
// Split ognl except when this is not a Map, Array
// and we would like to keep the dots within the key name
List<String> methods = OgnlHelper.splitOgnl(ognl);
String key = methods.get(0);
String keySuffix = "";
// if ognl starts with a key inside brackets (eg: [foo.bar])
// remove starting and ending brackets from key
if (key.startsWith("[") && key.endsWith("]")) {
key = StringHelper.removeLeadingAndEndingQuotes(key.substring(1, key.length() - 1));
keySuffix = StringHelper.after(methods.get(0), key);
}
// remove any OGNL operators so we got the pure key name
key = OgnlHelper.removeOperators(key);
property = keyedEntityRetrievalStrategy.getKeyedEntity(exchange, key);
if (property == null) {
return null;
}
// the remainder is the rest of the ognl without the key
String remainder = ObjectHelper.after(ognl, key + keySuffix);
return new MethodCallExpression(property, remainder).evaluate(exchange);
}
@Override
public String toString() {
return toStringValue;
}
/**
* Strategy to retrieve the value based on the key
*/
public interface KeyedEntityRetrievalStrategy {
Object getKeyedEntity(Exchange exchange, String key);
}
}
}
|
camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java
|
/**
* 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.camel.builder;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.Component;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.NoSuchEndpointException;
import org.apache.camel.NoSuchLanguageException;
import org.apache.camel.NoTypeConversionAvailableException;
import org.apache.camel.Producer;
import org.apache.camel.RuntimeExchangeException;
import org.apache.camel.component.bean.BeanInvocation;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.language.bean.BeanLanguage;
import org.apache.camel.language.simple.SimpleLanguage;
import org.apache.camel.model.language.MethodCallExpression;
import org.apache.camel.processor.DefaultExchangeFormatter;
import org.apache.camel.spi.ExchangeFormatter;
import org.apache.camel.spi.Language;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.spi.UnitOfWork;
import org.apache.camel.support.ExpressionAdapter;
import org.apache.camel.support.TokenPairExpressionIterator;
import org.apache.camel.support.TokenXMLExpressionIterator;
import org.apache.camel.support.XMLTokenExpressionIterator;
import org.apache.camel.util.CamelContextHelper;
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.GroupIterator;
import org.apache.camel.util.GroupTokenIterator;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.MessageHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.OgnlHelper;
import org.apache.camel.util.SkipIterator;
import org.apache.camel.util.StringHelper;
/**
* A helper class for working with <a href="http://camel.apache.org/expression.html">expressions</a>.
*
* @version
*/
public final class ExpressionBuilder {
private static final Pattern OFFSET_PATTERN = Pattern.compile("([+-])([^+-]+)");
/**
* Utility classes should not have a public constructor.
*/
private ExpressionBuilder() {
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentObjectsExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachmentObjects();
}
@Override
public String toString() {
return "attachmentObjects";
}
};
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentObjectValuesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachmentObjects().values();
}
@Override
public String toString() {
return "attachmentObjects";
}
};
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentsExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachments();
}
@Override
public String toString() {
return "attachments";
}
};
}
/**
* Returns an expression for the inbound message attachments
*
* @return an expression object which will return the inbound message attachments
*/
public static Expression attachmentValuesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getAttachments().values();
}
@Override
public String toString() {
return "attachments";
}
};
}
/**
* Returns an expression for the header value with the given name
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @return an expression object which will return the header value
*/
public static Expression headerExpression(final String headerName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = simpleExpression(headerName).evaluate(exchange, String.class);
Object header = exchange.getIn().getHeader(name);
if (header == null) {
// fall back on a property
header = exchange.getProperty(name);
}
return header;
}
@Override
public String toString() {
return "header(" + headerName + ")";
}
};
}
/**
* Returns an expression for the header value with the given name converted to the given type
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @param type the type to convert to
* @return an expression object which will return the header value
*/
public static <T> Expression headerExpression(final String headerName, final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = simpleExpression(headerName).evaluate(exchange, String.class);
Object header = exchange.getIn().getHeader(name, type);
if (header == null) {
// fall back on a property
header = exchange.getProperty(name, type);
}
return header;
}
@Override
public String toString() {
return "headerAs(" + headerName + ", " + type + ")";
}
};
}
/**
* Returns an expression for the header value with the given name converted to the given type
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @param typeName the type to convert to as a FQN class name
* @return an expression object which will return the header value
*/
public static Expression headerExpression(final String headerName, final String typeName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Class<?> type;
try {
String text = simpleExpression(typeName).evaluate(exchange, String.class);
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
String text = simpleExpression(headerName).evaluate(exchange, String.class);
Object header = exchange.getIn().getHeader(text, type);
if (header == null) {
// fall back on a property
header = exchange.getProperty(text, type);
}
return header;
}
@Override
public String toString() {
return "headerAs(" + headerName + ", " + typeName + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message header invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the header in a simple OGNL syntax
*/
public static Expression headersOgnlExpression(final String ognl) {
return new KeyedOgnlExpressionAdapter(ognl, "headerOgnl(" + ognl + ")",
new KeyedOgnlExpressionAdapter.KeyedEntityRetrievalStrategy() {
public Object getKeyedEntity(Exchange exchange, String key) {
String text = simpleExpression(key).evaluate(exchange, String.class);
return exchange.getIn().getHeader(text);
}
});
}
/**
* Returns an expression for the inbound message headers
*
* @return an expression object which will return the inbound headers
*/
public static Expression headersExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeaders();
}
@Override
public String toString() {
return "headers";
}
};
}
/**
* Returns an expression for the out header value with the given name
* <p/>
* Will fallback and look in properties if not found in headers.
*
* @param headerName the name of the header the expression will return
* @return an expression object which will return the header value
*/
public static Expression outHeaderExpression(final String headerName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (!exchange.hasOut()) {
return null;
}
String text = simpleExpression(headerName).evaluate(exchange, String.class);
Message out = exchange.getOut();
Object header = out.getHeader(text);
if (header == null) {
// let's try the exchange header
header = exchange.getProperty(text);
}
return header;
}
@Override
public String toString() {
return "outHeader(" + headerName + ")";
}
};
}
/**
* Returns an expression for the outbound message headers
*
* @return an expression object which will return the headers, will be <tt>null</tt> if the
* exchange is not out capable.
*/
public static Expression outHeadersExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// only get out headers if the MEP is out capable
if (ExchangeHelper.isOutCapable(exchange)) {
return exchange.getOut().getHeaders();
} else {
return null;
}
}
@Override
public String toString() {
return "outHeaders";
}
};
}
/**
* Returns an expression for the exchange pattern
*
* @see org.apache.camel.Exchange#getPattern()
* @return an expression object which will return the exchange pattern
*/
public static Expression exchangePatternExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getPattern();
}
@Override
public String toString() {
return "exchangePattern";
}
};
}
/**
* Returns an expression for an exception set on the exchange
*
* @see Exchange#getException()
* @return an expression object which will return the exception set on the exchange
*/
public static Expression exchangeExceptionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
return exception;
}
@Override
public String toString() {
return "exchangeException";
}
};
}
/**
* Returns an expression for an exception set on the exchange
* <p/>
* Is used to get the caused exception that typically have been wrapped in some sort
* of Camel wrapper exception
* @param type the exception type
* @see Exchange#getException(Class)
* @return an expression object which will return the exception set on the exchange
*/
public static Expression exchangeExceptionExpression(final Class<Exception> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException(type);
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
return ObjectHelper.getException(type, exception);
}
return exception;
}
@Override
public String toString() {
return "exchangeException[" + type + "]";
}
};
}
/**
* Returns the expression for the exchanges exception invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the body in a simple OGNL syntax
*/
public static Expression exchangeExceptionOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
if (exception == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(exception, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "exchangeExceptionOgnl(" + ognl + ")";
}
};
}
/**
* Returns an expression for the type converter
*
* @return an expression object which will return the type converter
*/
public static Expression typeConverterExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getTypeConverter();
}
@Override
public String toString() {
return "typeConverter";
}
};
}
/**
* Returns an expression for the {@link org.apache.camel.spi.Registry}
*
* @return an expression object which will return the registry
*/
public static Expression registryExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getRegistry();
}
@Override
public String toString() {
return "registry";
}
};
}
/**
* Returns an expression for lookup a bean in the {@link org.apache.camel.spi.Registry}
*
* @return an expression object which will return the bean
*/
public static Expression refExpression(final String ref) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(ref).evaluate(exchange, String.class);
return exchange.getContext().getRegistry().lookupByName(text);
}
@Override
public String toString() {
return "ref(" + ref + ")";
}
};
}
/**
* Returns an expression for the {@link org.apache.camel.CamelContext}
*
* @return an expression object which will return the camel context
*/
public static Expression camelContextExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext();
}
@Override
public String toString() {
return "camelContext";
}
};
}
/**
* Returns an expression for the {@link org.apache.camel.CamelContext} name
*
* @return an expression object which will return the camel context name
*/
public static Expression camelContextNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getName();
}
@Override
public String toString() {
return "camelContextName";
}
};
}
/**
* Returns an expression for an exception message set on the exchange
*
* @see <tt>Exchange.getException().getMessage()</tt>
* @return an expression object which will return the exception message set on the exchange
*/
public static Expression exchangeExceptionMessageExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
return exception != null ? exception.getMessage() : null;
}
@Override
public String toString() {
return "exchangeExceptionMessage";
}
};
}
/**
* Returns an expression for an exception stacktrace set on the exchange
*
* @return an expression object which will return the exception stacktrace set on the exchange
*/
public static Expression exchangeExceptionStackTraceExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Exception exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
}
if (exception != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
IOHelper.close(pw, sw);
return sw.toString();
} else {
return null;
}
}
@Override
public String toString() {
return "exchangeExceptionStackTrace";
}
};
}
/**
* Returns an expression for the property value of exchange with the given name
*
* @param propertyName the name of the property the expression will return
* @return an expression object which will return the property value
* @deprecated use {@link #exchangePropertyExpression(String)} instead
*/
@Deprecated
public static Expression propertyExpression(final String propertyName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
return exchange.getProperty(text);
}
@Override
public String toString() {
return "exchangeProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for the property value of exchange with the given name
*
* @param propertyName the name of the property the expression will return
* @return an expression object which will return the property value
*/
public static Expression exchangePropertyExpression(final String propertyName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
return exchange.getProperty(text);
}
@Override
public String toString() {
return "exchangeProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for the property value of exchange with the given name invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the property in a simple OGNL syntax
*/
public static Expression propertyOgnlExpression(final String ognl) {
return new KeyedOgnlExpressionAdapter(ognl, "propertyOgnl(" + ognl + ")",
new KeyedOgnlExpressionAdapter.KeyedEntityRetrievalStrategy() {
public Object getKeyedEntity(Exchange exchange, String key) {
String text = simpleExpression(key).evaluate(exchange, String.class);
return exchange.getProperty(text);
}
});
}
/**
* Returns an expression for the properties of exchange
*
* @return an expression object which will return the properties
* @deprecated use {@link #exchangeExceptionExpression()} instead
*/
@Deprecated
public static Expression propertiesExpression() {
return exchangeExceptionExpression();
}
/**
* Returns an expression for the exchange properties of exchange
*
* @return an expression object which will return the exchange properties
*/
public static Expression exchangePropertiesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getProperties();
}
@Override
public String toString() {
return "exchangeProperties";
}
};
}
/**
* Returns an expression for the properties of the camel context
*
* @return an expression object which will return the properties
*/
public static Expression camelContextPropertiesExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getContext().getGlobalOptions();
}
@Override
public String toString() {
return "camelContextProperties";
}
};
}
/**
* Returns an expression for the property value of the camel context with the given name
*
* @param propertyName the name of the property the expression will return
* @return an expression object which will return the property value
*/
public static Expression camelContextPropertyExpression(final String propertyName) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
return exchange.getContext().getGlobalOption(text);
}
@Override
public String toString() {
return "camelContextProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for a system property value with the given name
*
* @param propertyName the name of the system property the expression will return
* @return an expression object which will return the system property value
*/
public static Expression systemPropertyExpression(final String propertyName) {
return systemPropertyExpression(propertyName, null);
}
/**
* Returns an expression for a system property value with the given name
*
* @param propertyName the name of the system property the expression will return
* @param defaultValue default value to return if no system property exists
* @return an expression object which will return the system property value
*/
public static Expression systemPropertyExpression(final String propertyName,
final String defaultValue) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
String text2 = simpleExpression(defaultValue).evaluate(exchange, String.class);
return System.getProperty(text, text2);
}
@Override
public String toString() {
return "systemProperty(" + propertyName + ")";
}
};
}
/**
* Returns an expression for a system environment value with the given name
*
* @param propertyName the name of the system environment the expression will return
* @return an expression object which will return the system property value
*/
public static Expression systemEnvironmentExpression(final String propertyName) {
return systemEnvironmentExpression(propertyName, null);
}
/**
* Returns an expression for a system environment value with the given name
*
* @param propertyName the name of the system environment the expression will return
* @param defaultValue default value to return if no system environment exists
* @return an expression object which will return the system environment value
*/
public static Expression systemEnvironmentExpression(final String propertyName,
final String defaultValue) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(propertyName).evaluate(exchange, String.class);
String answer = System.getenv(text);
if (answer == null) {
String text2 = simpleExpression(defaultValue).evaluate(exchange, String.class);
answer = text2;
}
return answer;
}
@Override
public String toString() {
return "systemEnvironment(" + propertyName + ")";
}
};
}
/**
* Returns an expression for the constant value
*
* @param value the value the expression will return
* @return an expression object which will return the constant value
*/
public static Expression constantExpression(final Object value) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return value;
}
@Override
public String toString() {
return "" + value;
}
};
}
/**
* Returns an expression for evaluating the expression/predicate using the given language
*
* @param expression the expression or predicate
* @return an expression object which will evaluate the expression/predicate using the given language
*/
public static Expression languageExpression(final String language, final String expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Language lan = exchange.getContext().resolveLanguage(language);
if (lan != null) {
return lan.createExpression(expression).evaluate(exchange, Object.class);
} else {
throw new NoSuchLanguageException(language);
}
}
@Override
public boolean matches(Exchange exchange) {
Language lan = exchange.getContext().resolveLanguage(language);
if (lan != null) {
return lan.createPredicate(expression).matches(exchange);
} else {
throw new NoSuchLanguageException(language);
}
}
@Override
public String toString() {
return "language[" + language + ":" + expression + "]";
}
};
}
/**
* Returns an expression for a type value
*
* @param name the type name
* @return an expression object which will return the type value
*/
public static Expression typeExpression(final String name) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// it may refer to a class type
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type = exchange.getContext().getClassResolver().resolveClass(text);
if (type != null) {
return type;
}
int pos = text.lastIndexOf(".");
if (pos > 0) {
String before = text.substring(0, pos);
String after = text.substring(pos + 1);
type = exchange.getContext().getClassResolver().resolveClass(before);
if (type != null) {
return ObjectHelper.lookupConstantFieldValue(type, after);
}
}
throw ObjectHelper.wrapCamelExecutionException(exchange, new ClassNotFoundException("Cannot find type " + text));
}
@Override
public String toString() {
return "type:" + name;
}
};
}
/**
* Returns an expression that caches the evaluation of another expression
* and returns the cached value, to avoid re-evaluating the expression.
*
* @param expression the target expression to cache
* @return the cached value
*/
public static Expression cacheExpression(final Expression expression) {
return new ExpressionAdapter() {
private final AtomicReference<Object> cache = new AtomicReference<Object>();
public Object evaluate(Exchange exchange) {
Object answer = cache.get();
if (answer == null) {
answer = expression.evaluate(exchange, Object.class);
cache.set(answer);
}
return answer;
}
@Override
public String toString() {
return expression.toString();
}
};
}
/**
* Returns the expression for the exchanges inbound message body
*/
public static Expression bodyExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getBody();
}
@Override
public String toString() {
return "body";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body
*/
public static Expression bodyExpression(final Function<Object, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody()
);
}
@Override
public String toString() {
return "bodyExpression";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body and headers
*/
public static Expression bodyExpression(final BiFunction<Object, Map<String, Object>, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody(),
exchange.getIn().getHeaders()
);
}
@Override
public String toString() {
return "bodyExpression";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body converted to a desired type
*/
public static <T> Expression bodyExpression(final Class<T> bodyType, final Function<T, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody(bodyType)
);
}
@Override
public String toString() {
return "bodyExpression (" + bodyType + ")";
}
};
}
/**
* Returns a functional expression for the exchanges inbound message body converted to a desired type and headers
*/
public static <T> Expression bodyExpression(final Class<T> bodyType, final BiFunction<T, Map<String, Object>, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(
exchange.getIn().getBody(bodyType),
exchange.getIn().getHeaders()
);
}
@Override
public String toString() {
return "bodyExpression (" + bodyType + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message body invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the body in a simple OGNL syntax
*/
public static Expression bodyOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object body = exchange.getIn().getBody();
if (body == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(body, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "bodyOgnl(" + ognl + ")";
}
};
}
/**
* Returns the expression for invoking a method (support OGNL syntax) on the given expression
*
* @param exp the expression to evaluate and invoke the method on its result
* @param ognl methods to invoke on the evaluated expression in a simple OGNL syntax
*/
public static Expression ognlExpression(final Expression exp, final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object value = exp.evaluate(exchange, Object.class);
if (value == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(value, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "ognl(" + exp + ", " + ognl + ")";
}
};
}
/**
* Returns the expression for the exchanges camelContext invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the context in a simple OGNL syntax
*/
public static Expression camelContextOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
CamelContext context = exchange.getContext();
if (context == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(context, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "camelContextOgnl(" + ognl + ")";
}
};
}
/**
* Returns the expression for the exchange invoking methods defined
* in a simple OGNL notation
*
* @param ognl methods to invoke on the exchange in a simple OGNL syntax
*/
public static Expression exchangeOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
return new MethodCallExpression(exchange, ognl).evaluate(exchange);
}
@Override
public String toString() {
return "exchangeOgnl(" + ognl + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*/
public static <T> Expression bodyExpression(final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getBody(type);
}
@Override
public String toString() {
return "bodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*/
public static Expression bodyExpression(final String name) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
return exchange.getIn().getBody(type);
}
@Override
public String toString() {
return "bodyAs[" + name + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type and invoking methods on the converted body defined in a simple OGNL notation
*/
public static Expression bodyOgnlExpression(final String name, final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
Object body = exchange.getIn().getBody(type);
if (body != null) {
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
MethodCallExpression call = new MethodCallExpression(exchange, ognl);
// set the instance to use
call.setInstance(body);
return call.evaluate(exchange);
} else {
return null;
}
}
@Override
public String toString() {
return "bodyOgnlAs[" + name + "](" + ognl + ")";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*/
public static Expression mandatoryBodyExpression(final String name) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
try {
return exchange.getIn().getMandatoryBody(type);
} catch (InvalidPayloadException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
}
@Override
public String toString() {
return "mandatoryBodyAs[" + name + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type and invoking methods on the converted body defined in a simple OGNL notation
*/
public static Expression mandatoryBodyOgnlExpression(final String name, final String ognl) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(name).evaluate(exchange, String.class);
Class<?> type;
try {
type = exchange.getContext().getClassResolver().resolveMandatoryClass(text);
} catch (ClassNotFoundException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
Object body;
try {
body = exchange.getIn().getMandatoryBody(type);
} catch (InvalidPayloadException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
MethodCallExpression call = new MethodCallExpression(exchange, ognl);
// set the instance to use
call.setInstance(body);
return call.evaluate(exchange);
}
@Override
public String toString() {
return "mandatoryBodyAs[" + name + "](" + ognl + ")";
}
};
}
/**
* Returns the expression for the current thread name
*/
public static Expression threadNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return Thread.currentThread().getName();
}
@Override
public String toString() {
return "threadName";
}
};
}
/**
* Returns the expression for the {@code null} value
*/
public static Expression nullExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return null;
}
@Override
public String toString() {
return "null";
}
};
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type.
* <p/>
* Does <b>not</b> allow null bodies.
*/
public static <T> Expression mandatoryBodyExpression(final Class<T> type) {
return mandatoryBodyExpression(type, false);
}
/**
* Returns the expression for the exchanges inbound message body converted
* to the given type
*
* @param type the type
* @param nullBodyAllowed whether null bodies is allowed and if so a null is returned,
* otherwise an exception is thrown
*/
public static <T> Expression mandatoryBodyExpression(final Class<T> type, final boolean nullBodyAllowed) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (nullBodyAllowed) {
if (exchange.getIn().getBody() == null) {
return null;
}
// if its a bean invocation then if it has no arguments then it should be threaded as null body allowed
if (exchange.getIn().getBody() instanceof BeanInvocation) {
// BeanInvocation would be stored directly as the message body
// do not force any type conversion attempts as it would just be unnecessary and cost a bit performance
// so a regular instanceof check is sufficient
BeanInvocation bi = (BeanInvocation) exchange.getIn().getBody();
if (bi.getArgs() == null || bi.getArgs().length == 0 || bi.getArgs()[0] == null) {
return null;
}
}
}
try {
return exchange.getIn().getMandatoryBody(type);
} catch (InvalidPayloadException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
}
@Override
public String toString() {
return "mandatoryBodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the exchanges inbound message body type
*/
public static Expression bodyTypeExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getBody().getClass();
}
@Override
public String toString() {
return "bodyType";
}
};
}
/**
* Returns the expression for the out messages body
*/
public static Expression outBodyExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (exchange.hasOut()) {
return exchange.getOut().getBody();
} else {
return null;
}
}
@Override
public String toString() {
return "outBody";
}
};
}
/**
* Returns the expression for the exchanges outbound message body converted
* to the given type
*/
public static <T> Expression outBodyExpression(final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (exchange.hasOut()) {
return exchange.getOut().getBody(type);
} else {
return null;
}
}
@Override
public String toString() {
return "outBodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the fault messages body
*/
public static Expression faultBodyExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
return msg.isFault() ? msg.getBody() : null;
}
@Override
public String toString() {
return "faultBody";
}
};
}
/**
* Returns the expression for the exchanges fault message body converted
* to the given type
*/
public static <T> Expression faultBodyExpression(final Class<T> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
return msg.isFault() ? msg.getBody(type) : null;
}
@Override
public String toString() {
return "faultBodyAs[" + type.getName() + "]";
}
};
}
/**
* Returns the expression for the exchange
*/
public static Expression exchangeExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange;
}
@Override
public String toString() {
return "exchange";
}
};
}
/**
* Returns a functional expression for the exchange
*/
public static Expression exchangeExpression(final Function<Exchange, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(exchange);
}
@Override
public String toString() {
return "exchangeExpression";
}
};
}
/**
* Returns the expression for the IN message
*/
public static Expression messageExpression() {
return inMessageExpression();
}
/**
* Returns a functional expression for the IN message
*/
public static Expression messageExpression(final Function<Message, Object> function) {
return inMessageExpression(function);
}
/**
* Returns the expression for the IN message
*/
public static Expression inMessageExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn();
}
@Override
public String toString() {
return "inMessage";
}
};
}
/**
* Returns a functional expression for the IN message
*/
public static Expression inMessageExpression(final Function<Message, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(exchange.getIn());
}
@Override
public String toString() {
return "inMessageExpression";
}
};
}
/**
* Returns the expression for the OUT message
*/
public static Expression outMessageExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getOut();
}
@Override
public String toString() {
return "outMessage";
}
};
}
/**
* Returns a functional expression for the OUT message
*/
public static Expression outMessageExpression(final Function<Message, Object> function) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return function.apply(exchange.getOut());
}
@Override
public String toString() {
return "outMessageExpression";
}
};
}
/**
* Returns an expression which converts the given expression to the given type
*/
public static Expression convertToExpression(final Expression expression, final Class<?> type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (type != null) {
return expression.evaluate(exchange, type);
} else {
return expression;
}
}
@Override
public String toString() {
return "" + expression;
}
};
}
/**
* Returns an expression which converts the given expression to the given type the type
* expression is evaluated to
*/
public static Expression convertToExpression(final Expression expression, final Expression type) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object result = type.evaluate(exchange, Object.class);
if (result != null) {
return expression.evaluate(exchange, result.getClass());
} else {
return expression;
}
}
@Override
public String toString() {
return "" + expression;
}
};
}
/**
* Returns a tokenize expression which will tokenize the string with the
* given token
*/
public static Expression tokenizeExpression(final Expression expression,
final String token) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(token).evaluate(exchange, String.class);
Object value = expression.evaluate(exchange, Object.class);
Scanner scanner = ObjectHelper.getScanner(exchange, value);
scanner.useDelimiter(text);
return scanner;
}
@Override
public String toString() {
return "tokenize(" + expression + ", " + token + ")";
}
};
}
/**
* Returns an expression that skips the first element
*/
public static Expression skipFirstExpression(final Expression expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object value = expression.evaluate(exchange, Object.class);
Iterator it = exchange.getContext().getTypeConverter().tryConvertTo(Iterator.class, exchange, value);
if (it != null) {
// skip first
it.next();
return it;
} else {
return value;
}
}
@Override
public String toString() {
return "skipFirst(" + expression + ")";
}
};
}
/**
* Returns an {@link TokenPairExpressionIterator} expression
*/
public static Expression tokenizePairExpression(String startToken, String endToken, boolean includeTokens) {
return new TokenPairExpressionIterator(startToken, endToken, includeTokens);
}
/**
* Returns an {@link TokenXMLExpressionIterator} expression
*/
public static Expression tokenizeXMLExpression(String tagName, String inheritNamespaceTagName) {
ObjectHelper.notEmpty(tagName, "tagName");
return new TokenXMLExpressionIterator(tagName, inheritNamespaceTagName);
}
public static Expression tokenizeXMLAwareExpression(String path, char mode) {
ObjectHelper.notEmpty(path, "path");
return new XMLTokenExpressionIterator(path, mode);
}
public static Expression tokenizeXMLAwareExpression(String path, char mode, int group) {
ObjectHelper.notEmpty(path, "path");
return new XMLTokenExpressionIterator(path, mode, group);
}
/**
* Returns a tokenize expression which will tokenize the string with the
* given regex
*/
public static Expression regexTokenizeExpression(final Expression expression,
final String regexTokenizer) {
final Pattern pattern = Pattern.compile(regexTokenizer);
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Object value = expression.evaluate(exchange, Object.class);
Scanner scanner = ObjectHelper.getScanner(exchange, value);
scanner.useDelimiter(pattern);
return scanner;
}
@Override
public String toString() {
return "regexTokenize(" + expression + ", " + pattern.pattern() + ")";
}
};
}
public static Expression groupXmlIteratorExpression(final Expression expression, final String group) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// evaluate expression as iterator
Iterator<?> it = expression.evaluate(exchange, Iterator.class);
ObjectHelper.notNull(it, "expression: " + expression + " evaluated on " + exchange + " must return an java.util.Iterator");
// must use GroupTokenIterator in xml mode as we want to concat the xml parts into a single message
// the group can be a simple expression so evaluate it as a number
Integer parts = exchange.getContext().resolveLanguage("simple").createExpression(group).evaluate(exchange, Integer.class);
if (parts == null) {
throw new RuntimeExchangeException("Group evaluated as null, must be evaluated as a positive Integer value from expression: " + group, exchange);
} else if (parts <= 0) {
throw new RuntimeExchangeException("Group must be a positive number, was: " + parts, exchange);
}
return new GroupTokenIterator(exchange, it, null, parts, false);
}
@Override
public String toString() {
return "group " + expression + " " + group + " times";
}
};
}
public static Expression groupIteratorExpression(final Expression expression, final String token, final String group, final boolean skipFirst) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// evaluate expression as iterator
Iterator<?> it = expression.evaluate(exchange, Iterator.class);
ObjectHelper.notNull(it, "expression: " + expression + " evaluated on " + exchange + " must return an java.util.Iterator");
// the group can be a simple expression so evaluate it as a number
Integer parts = exchange.getContext().resolveLanguage("simple").createExpression(group).evaluate(exchange, Integer.class);
if (parts == null) {
throw new RuntimeExchangeException("Group evaluated as null, must be evaluated as a positive Integer value from expression: " + group, exchange);
} else if (parts <= 0) {
throw new RuntimeExchangeException("Group must be a positive number, was: " + parts, exchange);
}
if (token != null) {
return new GroupTokenIterator(exchange, it, token, parts, skipFirst);
} else {
return new GroupIterator(exchange, it, parts, skipFirst);
}
}
@Override
public String toString() {
return "group " + expression + " " + group + " times";
}
};
}
public static Expression skipIteratorExpression(final Expression expression, final int skip) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// evaluate expression as iterator
Iterator<?> it = expression.evaluate(exchange, Iterator.class);
ObjectHelper.notNull(it, "expression: " + expression + " evaluated on " + exchange + " must return an java.util.Iterator");
return new SkipIterator(exchange, it, skip);
}
@Override
public String toString() {
return "skip " + expression + " " + skip + " times";
}
};
}
/**
* Returns a sort expression which will sort the expression with the given comparator.
* <p/>
* The expression is evaluated as a {@link List} object to allow sorting.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static Expression sortExpression(final Expression expression, final Comparator comparator) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
List<?> list = expression.evaluate(exchange, List.class);
list.sort(comparator);
return list;
}
@Override
public String toString() {
return "sort(" + expression + " by: " + comparator + ")";
}
};
}
/**
* Transforms the expression into a String then performs the regex
* replaceAll to transform the String and return the result
*/
public static Expression regexReplaceAll(final Expression expression,
final String regex, final String replacement) {
final Pattern pattern = Pattern.compile(regex);
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = expression.evaluate(exchange, String.class);
if (text == null) {
return null;
}
return pattern.matcher(text).replaceAll(replacement);
}
@Override
public String toString() {
return "regexReplaceAll(" + expression + ", " + pattern.pattern() + ")";
}
};
}
/**
* Transforms the expression into a String then performs the regex
* replaceAll to transform the String and return the result
*/
public static Expression regexReplaceAll(final Expression expression,
final String regex, final Expression replacementExpression) {
final Pattern pattern = Pattern.compile(regex);
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = expression.evaluate(exchange, String.class);
String replacement = replacementExpression.evaluate(exchange, String.class);
if (text == null || replacement == null) {
return null;
}
return pattern.matcher(text).replaceAll(replacement);
}
@Override
public String toString() {
return "regexReplaceAll(" + expression + ", " + pattern.pattern() + ")";
}
};
}
/**
* Appends the String evaluations of the two expressions together
*/
public static Expression append(final Expression left, final Expression right) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return left.evaluate(exchange, String.class) + right.evaluate(exchange, String.class);
}
@Override
public String toString() {
return "append(" + left + ", " + right + ")";
}
};
}
/**
* Prepends the String evaluations of the two expressions together
*/
public static Expression prepend(final Expression left, final Expression right) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return right.evaluate(exchange, String.class) + left.evaluate(exchange, String.class);
}
@Override
public String toString() {
return "prepend(" + left + ", " + right + ")";
}
};
}
/**
* Returns an expression which returns the string concatenation value of the various
* expressions
*
* @param expressions the expression to be concatenated dynamically
* @return an expression which when evaluated will return the concatenated values
*/
public static Expression concatExpression(final Collection<Expression> expressions) {
return concatExpression(expressions, null);
}
/**
* Returns an expression which returns the string concatenation value of the various
* expressions
*
* @param expressions the expression to be concatenated dynamically
* @param desription the text description of the expression
* @return an expression which when evaluated will return the concatenated values
*/
public static Expression concatExpression(final Collection<Expression> expressions, final String desription) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
StringBuilder buffer = new StringBuilder();
for (Expression expression : expressions) {
String text = expression.evaluate(exchange, String.class);
if (text != null) {
buffer.append(text);
}
}
return buffer.toString();
}
@Override
public String toString() {
if (desription != null) {
return desription;
} else {
return "concat" + expressions;
}
}
};
}
/**
* Returns an Expression for the inbound message id
*/
public static Expression messageIdExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getMessageId();
}
@Override
public String toString() {
return "messageId";
}
};
}
/**
* Returns an Expression for the exchange id
*/
public static Expression exchangeIdExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getExchangeId();
}
@Override
public String toString() {
return "exchangeId";
}
};
}
/**
* Returns an Expression for the route id
*/
public static Expression routeIdExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String answer = null;
UnitOfWork uow = exchange.getUnitOfWork();
RouteContext rc = uow != null ? uow.getRouteContext() : null;
if (rc != null) {
answer = rc.getRoute().getId();
}
if (answer == null) {
// fallback and get from route id on the exchange
answer = exchange.getFromRouteId();
}
return answer;
}
@Override
public String toString() {
return "routeId";
}
};
}
public static Expression dateExpression(final String command) {
return dateExpression(command, null, null);
}
public static Expression dateExpression(final String command, final String pattern) {
return dateExpression(command, null, pattern);
}
public static Expression dateExpression(final String commandWithOffsets, final String timezone, final String pattern) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// Capture optional time offsets
String command = commandWithOffsets.split("[+-]", 2)[0].trim();
List<Long> offsets = new ArrayList<>();
Matcher offsetMatcher = OFFSET_PATTERN.matcher(commandWithOffsets);
while (offsetMatcher.find()) {
try {
long value = exchange.getContext().getTypeConverter().mandatoryConvertTo(long.class, exchange, offsetMatcher.group(2).trim());
offsets.add(offsetMatcher.group(1).equals("+") ? value : -value);
} catch (NoTypeConversionAvailableException e) {
throw ObjectHelper.wrapCamelExecutionException(exchange, e);
}
}
Date date;
if ("now".equals(command)) {
date = new Date();
} else if (command.startsWith("header.") || command.startsWith("in.header.")) {
String key = command.substring(command.lastIndexOf('.') + 1);
date = exchange.getIn().getHeader(key, Date.class);
if (date == null) {
throw new IllegalArgumentException("Cannot find java.util.Date object at command: " + command);
}
} else if (command.startsWith("out.header.")) {
String key = command.substring(command.lastIndexOf('.') + 1);
date = exchange.getOut().getHeader(key, Date.class);
if (date == null) {
throw new IllegalArgumentException("Cannot find java.util.Date object at command: " + command);
}
} else if ("file".equals(command)) {
Long num = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Long.class);
if (num != null && num > 0) {
date = new Date(num);
} else {
date = exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Date.class);
if (date == null) {
throw new IllegalArgumentException("Cannot find " + Exchange.FILE_LAST_MODIFIED + " header at command: " + command);
}
}
} else {
throw new IllegalArgumentException("Command not supported for dateExpression: " + command);
}
// Apply offsets
long dateAsLong = date.getTime();
for (long offset : offsets) {
dateAsLong += offset;
}
date = new Date(dateAsLong);
if (pattern != null && !pattern.isEmpty()) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
if (timezone != null && !timezone.isEmpty()) {
df.setTimeZone(TimeZone.getTimeZone(timezone));
}
return df.format(date);
} else {
return date;
}
}
@Override
public String toString() {
return "date(" + commandWithOffsets + ":" + pattern + ":" + timezone + ")";
}
};
}
public static Expression simpleExpression(final String expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
if (SimpleLanguage.hasSimpleFunction(expression)) {
// resolve language using context to have a clear separation of packages
// must call evaluate to return the nested language evaluate when evaluating
// stacked expressions
Language language = exchange.getContext().resolveLanguage("simple");
return language.createExpression(expression).evaluate(exchange, Object.class);
} else {
return expression;
}
}
@Override
public String toString() {
return "simple(" + expression + ")";
}
};
}
public static Expression beanExpression(final String expression) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// bean is able to evaluate method name if it contains nested functions
// so we should not eager evaluate expression as a string
// resolve language using context to have a clear separation of packages
// must call evaluate to return the nested language evaluate when evaluating
// stacked expressions
Language language = exchange.getContext().resolveLanguage("bean");
return language.createExpression(expression).evaluate(exchange, Object.class);
}
@Override
public String toString() {
return "bean(" + expression + ")";
}
};
}
public static Expression beanExpression(final Class<?> beanType, final String methodName) {
return BeanLanguage.bean(beanType, methodName);
}
public static Expression beanExpression(final Object bean, final String methodName) {
return BeanLanguage.bean(bean, methodName);
}
public static Expression beanExpression(final String beanRef, final String methodName) {
String expression = methodName != null ? beanRef + "." + methodName : beanRef;
return beanExpression(expression);
}
/**
* Returns an expression processing the exchange to the given endpoint uri
*
* @param uri endpoint uri to send the exchange to
* @return an expression object which will return the OUT body
*/
public static Expression toExpression(final String uri) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(uri).evaluate(exchange, String.class);
Endpoint endpoint = exchange.getContext().getEndpoint(text);
if (endpoint == null) {
throw new NoSuchEndpointException(text);
}
Producer producer;
try {
producer = endpoint.createProducer();
producer.start();
producer.process(exchange);
producer.stop();
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
// return the OUT body, but check for exchange pattern
if (ExchangeHelper.isOutCapable(exchange)) {
return exchange.getOut().getBody();
} else {
return exchange.getIn().getBody();
}
}
@Override
public String toString() {
return "to(" + uri + ")";
}
};
}
public static Expression fileNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
}
@Override
public String toString() {
return "file:name";
}
};
}
public static Expression fileOnlyNameExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String answer = exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY, String.class);
if (answer == null) {
answer = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
answer = FileUtil.stripPath(answer);
}
return answer;
}
@Override
public String toString() {
return "file:onlyname";
}
};
}
public static Expression fileNameNoExtensionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.stripExt(name);
}
@Override
public String toString() {
return "file:name.noext";
}
};
}
public static Expression fileNameNoExtensionSingleExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.stripExt(name, true);
}
@Override
public String toString() {
return "file:name.noext.single";
}
};
}
public static Expression fileOnlyNameNoExtensionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = fileOnlyNameExpression().evaluate(exchange, String.class);
return FileUtil.stripExt(name);
}
@Override
public String toString() {
return "file:onlyname.noext";
}
};
}
public static Expression fileOnlyNameNoExtensionSingleExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = fileOnlyNameExpression().evaluate(exchange, String.class);
return FileUtil.stripExt(name, true);
}
@Override
public String toString() {
return "file:onlyname.noext.single";
}
};
}
public static Expression fileExtensionExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.onlyExt(name);
}
@Override
public String toString() {
return "file:ext";
}
};
}
public static Expression fileExtensionSingleExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
return FileUtil.onlyExt(name, true);
}
@Override
public String toString() {
return "file:ext.single";
}
};
}
public static Expression fileParentExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFileParent", String.class);
}
@Override
public String toString() {
return "file:parent";
}
};
}
public static Expression filePathExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFilePath", String.class);
}
@Override
public String toString() {
return "file:path";
}
};
}
public static Expression fileAbsolutePathExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFileAbsolutePath", String.class);
}
@Override
public String toString() {
return "file:absolute.path";
}
};
}
public static Expression fileAbsoluteExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader("CamelFileAbsolute", Boolean.class);
}
@Override
public String toString() {
return "file:absolute";
}
};
}
public static Expression fileSizeExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader(Exchange.FILE_LENGTH, Long.class);
}
@Override
public String toString() {
return "file:length";
}
};
}
public static Expression fileLastModifiedExpression() {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
return exchange.getIn().getHeader(Exchange.FILE_LAST_MODIFIED, Long.class);
}
@Override
public String toString() {
return "file:modified";
}
};
}
/**
* Returns Simple expression or fallback to Constant expression if expression str is not Simple expression.
*/
public static Expression parseSimpleOrFallbackToConstantExpression(String str, CamelContext camelContext) {
if (StringHelper.hasStartToken(str, "simple")) {
return camelContext.resolveLanguage("simple").createExpression(str);
}
return constantExpression(str);
}
public static Expression propertiesComponentExpression(final String key, final String locations, final String defaultValue) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
String text = simpleExpression(key).evaluate(exchange, String.class);
String text2 = simpleExpression(locations).evaluate(exchange, String.class);
try {
if (text2 != null) {
// the properties component is optional as we got locations
// getComponent will create a new component if none already exists
Component component = exchange.getContext().getComponent("properties");
PropertiesComponent pc = exchange.getContext().getTypeConverter()
.mandatoryConvertTo(PropertiesComponent.class, component);
// enclose key with {{ }} to force parsing
String[] paths = text2.split(",");
return pc.parseUri(pc.getPrefixToken() + text + pc.getSuffixToken(), paths);
} else {
// the properties component is mandatory if no locations provided
Component component = exchange.getContext().hasComponent("properties");
if (component == null) {
throw new IllegalArgumentException("PropertiesComponent with name properties must be defined"
+ " in CamelContext to support property placeholders in expressions");
}
PropertiesComponent pc = exchange.getContext().getTypeConverter()
.mandatoryConvertTo(PropertiesComponent.class, component);
// enclose key with {{ }} to force parsing
return pc.parseUri(pc.getPrefixToken() + text + pc.getSuffixToken());
}
} catch (Exception e) {
// property with key not found, use default value if provided
if (defaultValue != null) {
return defaultValue;
}
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
@Override
public String toString() {
return "properties(" + key + ")";
}
};
}
/**
* Returns a random number between 0 and upperbound (exclusive)
*/
public static Expression randomExpression(final int upperbound) {
return randomExpression(0, upperbound);
}
/**
* Returns a random number between min and max
*/
public static Expression randomExpression(final int min, final int max) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
Random random = new Random();
int randomNum = random.nextInt(max - min) + min;
return randomNum;
}
@Override
public String toString() {
return "random";
}
};
}
/**
* Returns a random number between min and max
*/
public static Expression randomExpression(final String min, final String max) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
int num1 = simpleExpression(min).evaluate(exchange, Integer.class);
int num2 = simpleExpression(max).evaluate(exchange, Integer.class);
Random random = new Random();
int randomNum = random.nextInt(num2 - num1) + num1;
return randomNum;
}
@Override
public String toString() {
return "random";
}
};
}
/**
* Returns an iterator to skip (iterate) the given expression
*/
public static Expression skipExpression(final String expression, final int number) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// use simple language
Expression exp = exchange.getContext().resolveLanguage("simple").createExpression(expression);
return ExpressionBuilder.skipIteratorExpression(exp, number).evaluate(exchange, Object.class);
}
@Override
public String toString() {
return "skip(" + expression + "," + number + ")";
}
};
}
/**
* Returns an iterator to collate (iterate) the given expression
*/
public static Expression collateExpression(final String expression, final int group) {
return new ExpressionAdapter() {
public Object evaluate(Exchange exchange) {
// use simple language
Expression exp = exchange.getContext().resolveLanguage("simple").createExpression(expression);
return ExpressionBuilder.groupIteratorExpression(exp, null, "" + group, false).evaluate(exchange, Object.class);
}
@Override
public String toString() {
return "collate(" + expression + "," + group + ")";
}
};
}
/**
* Returns the message history (including exchange details or not)
*/
public static Expression messageHistoryExpression(final boolean detailed) {
return new ExpressionAdapter() {
private ExchangeFormatter formatter;
public Object evaluate(Exchange exchange) {
ExchangeFormatter ef = null;
if (detailed) {
// use the exchange formatter to log exchange details
ef = getOrCreateExchangeFormatter(exchange.getContext());
}
return MessageHelper.dumpMessageHistoryStacktrace(exchange, ef, false);
}
private ExchangeFormatter getOrCreateExchangeFormatter(CamelContext camelContext) {
if (formatter == null) {
Set<ExchangeFormatter> formatters = camelContext.getRegistry().findByType(ExchangeFormatter.class);
if (formatters != null && formatters.size() == 1) {
formatter = formatters.iterator().next();
} else {
// setup exchange formatter to be used for message history dump
DefaultExchangeFormatter def = new DefaultExchangeFormatter();
def.setShowExchangeId(true);
def.setMultiline(true);
def.setShowHeaders(true);
def.setStyle(DefaultExchangeFormatter.OutputStyle.Fixed);
try {
Integer maxChars = CamelContextHelper.parseInteger(camelContext, camelContext.getGlobalOption(Exchange.LOG_DEBUG_BODY_MAX_CHARS));
if (maxChars != null) {
def.setMaxChars(maxChars);
}
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
formatter = def;
}
}
return formatter;
}
@Override
public String toString() {
return "messageHistory(" + detailed + ")";
}
};
}
/**
* Expression adapter for OGNL expression from Message Header or Exchange property
*/
private static class KeyedOgnlExpressionAdapter extends ExpressionAdapter {
private final String ognl;
private final String toStringValue;
private final KeyedEntityRetrievalStrategy keyedEntityRetrievalStrategy;
KeyedOgnlExpressionAdapter(String ognl, String toStringValue,
KeyedEntityRetrievalStrategy keyedEntityRetrievalStrategy) {
this.ognl = ognl;
this.toStringValue = toStringValue;
this.keyedEntityRetrievalStrategy = keyedEntityRetrievalStrategy;
}
public Object evaluate(Exchange exchange) {
// try with full name first
Object property = keyedEntityRetrievalStrategy.getKeyedEntity(exchange, ognl);
if (property != null) {
return property;
}
// Split ognl except when this is not a Map, Array
// and we would like to keep the dots within the key name
List<String> methods = OgnlHelper.splitOgnl(ognl);
String key = methods.get(0);
String keySuffix = "";
// if ognl starts with a key inside brackets (eg: [foo.bar])
// remove starting and ending brackets from key
if (key.startsWith("[") && key.endsWith("]")) {
key = StringHelper.removeLeadingAndEndingQuotes(key.substring(1, key.length() - 1));
keySuffix = StringHelper.after(methods.get(0), key);
}
// remove any OGNL operators so we got the pure key name
key = OgnlHelper.removeOperators(key);
property = keyedEntityRetrievalStrategy.getKeyedEntity(exchange, key);
if (property == null) {
return null;
}
// the remainder is the rest of the ognl without the key
String remainder = ObjectHelper.after(ognl, key + keySuffix);
return new MethodCallExpression(property, remainder).evaluate(exchange);
}
@Override
public String toString() {
return toStringValue;
}
/**
* Strategy to retrieve the value based on the key
*/
public interface KeyedEntityRetrievalStrategy {
Object getKeyedEntity(Exchange exchange, String key);
}
}
}
|
Polished
|
camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java
|
Polished
|
<ide><path>amel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java
<ide> }
<ide>
<ide> /**
<del> * Returns a random number between 0 and upperbound (exclusive)
<del> */
<del> public static Expression randomExpression(final int upperbound) {
<del> return randomExpression(0, upperbound);
<del> }
<del>
<del> /**
<del> * Returns a random number between min and max
<add> * Returns a random number between 0 and max (exclusive)
<add> */
<add> public static Expression randomExpression(final int max) {
<add> return randomExpression(0, max);
<add> }
<add>
<add> /**
<add> * Returns a random number between min and max (exclusive)
<ide> */
<ide> public static Expression randomExpression(final int min, final int max) {
<ide> return new ExpressionAdapter() {
<ide>
<ide> @Override
<ide> public String toString() {
<del> return "random";
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * Returns a random number between min and max
<add> return "random(" + min + "," + max + ")";
<add> }
<add> };
<add> }
<add>
<add> /**
<add> * Returns a random number between min and max (exclusive)
<ide> */
<ide> public static Expression randomExpression(final String min, final String max) {
<ide> return new ExpressionAdapter() {
<ide>
<ide> @Override
<ide> public String toString() {
<del> return "random";
<add> return "random(" + min + "," + max + ")";
<ide> }
<ide> };
<ide> }
|
|
Java
|
apache-2.0
|
da363f845e9d20be2d99c9b8355462570f0df7f9
| 0 |
glyptodon/guacamole-client,necouchman/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,glyptodon/guacamole-client,necouchman/incubator-guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client,jmuehlner/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,glyptodon/guacamole-client,mike-jumper/incubator-guacamole-client,necouchman/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,glyptodon/guacamole-client
|
/*
* 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.guacamole.auth.quickconnect;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleSecurityException;
import org.apache.guacamole.net.GuacamoleTunnel;
import org.apache.guacamole.net.auth.AbstractConnectionGroup;
import org.apache.guacamole.net.auth.ConnectionGroup;
import org.apache.guacamole.protocol.GuacamoleClientInformation;
/**
* Provides a very simple, single-level connection group used
* for temporarily storing the QuickConnections created by
* users.
*/
public class QuickConnectConnectionGroup extends AbstractConnectionGroup {
/**
* The connection identifiers for this group.
*/
private Set<String> connectionIdentifiers;
/**
* Set up a QuickConnectConnectionGroup with a name and identifier, and
* an empty set of child connections.
*
* @param name
* The name of the QuickConnectConnectionGroup.
*
* @param identifier
* The identifier of the QuickConnectConnectionGroup.
*/
public QuickConnectConnectionGroup(String name, String identifier) {
setName(name);
setIdentifier(identifier);
setType(ConnectionGroup.Type.ORGANIZATIONAL);
this.connectionIdentifiers = new HashSet<String>(Collections.<String>emptyList());
}
/**
* Add a connection identifier to this connection group, and
* return the identifier if the add succeeds, else return null.
*
* @param identifier
* The identifier of the connection to add to the group.
*
* @return
* The String identifier of the connection if the add
* operation was successful; otherwise null.
*/
public String addConnectionIdentifier(String identifier) {
if (connectionIdentifiers.add(identifier))
return identifier;
return null;
}
@Override
public int getActiveConnections() {
return 0;
}
@Override
public Set<String> getConnectionIdentifiers() {
return connectionIdentifiers;
}
@Override
public Set<String> getConnectionGroupIdentifiers() {
return Collections.<String>emptySet();
}
@Override
public Map<String, String> getAttributes() {
return Collections.<String, String>emptyMap();
}
@Override
public void setAttributes(Map<String, String> attributes) {
// Do nothing - there are no attributes
}
@Override
public GuacamoleTunnel connect(GuacamoleClientInformation info)
throws GuacamoleException {
throw new GuacamoleSecurityException("Permission denied.");
}
}
|
extensions/guacamole-auth-quickconnect/src/main/java/org/apache/guacamole/auth/quickconnect/QuickConnectConnectionGroup.java
|
/*
* 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.guacamole.auth.quickconnect;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleSecurityException;
import org.apache.guacamole.net.GuacamoleTunnel;
import org.apache.guacamole.net.auth.AbstractConnectionGroup;
import org.apache.guacamole.net.auth.ConnectionGroup;
import org.apache.guacamole.protocol.GuacamoleClientInformation;
/**
* Provides a very simple, single-level connection group used
* for temporarily storing the QuickConnections created by
* users.
*/
class QuickConnectConnectionGroup extends AbstractConnectionGroup {
/**
* The connection identifiers for this group.
*/
private Set<String> connectionIdentifiers;
/**
* Set up a QuickConnectConnectionGroup with a name and identifier, and
* an empty set of child connections.
*
* @param name
* The name of the QuickConnectConnectionGroup.
*
* @param identifier
* The identifier of the QuickConnectConnectionGroup.
*/
public QuickConnectConnectionGroup(String name, String identifier) {
setName(name);
setIdentifier(identifier);
setType(ConnectionGroup.Type.ORGANIZATIONAL);
this.connectionIdentifiers = new HashSet<String>(Collections.<String>emptyList());
}
/**
* Add a connection identifier to this connection group, and
* return the identifier if the add succeeds, else return null.
*
* @param identifier
* The identifier of the connection to add to the group.
*
* @return
* The String identifier of the connection if the add
* operation was successful; otherwise null.
*/
public String addConnectionIdentifier(String identifier) {
if (connectionIdentifiers.add(identifier))
return identifier;
return null;
}
@Override
public int getActiveConnections() {
return 0;
}
@Override
public Set<String> getConnectionIdentifiers() {
return connectionIdentifiers;
}
@Override
public Set<String> getConnectionGroupIdentifiers() {
return Collections.<String>emptySet();
}
@Override
public Map<String, String> getAttributes() {
return Collections.<String, String>emptyMap();
}
@Override
public void setAttributes(Map<String, String> attributes) {
// Do nothing - there are no attributes
}
@Override
public GuacamoleTunnel connect(GuacamoleClientInformation info)
throws GuacamoleException {
throw new GuacamoleSecurityException("Permission denied.");
}
}
|
GUACAMOLE-38: Make class public for consistency with other classes.
|
extensions/guacamole-auth-quickconnect/src/main/java/org/apache/guacamole/auth/quickconnect/QuickConnectConnectionGroup.java
|
GUACAMOLE-38: Make class public for consistency with other classes.
|
<ide><path>xtensions/guacamole-auth-quickconnect/src/main/java/org/apache/guacamole/auth/quickconnect/QuickConnectConnectionGroup.java
<ide> * for temporarily storing the QuickConnections created by
<ide> * users.
<ide> */
<del>class QuickConnectConnectionGroup extends AbstractConnectionGroup {
<add>public class QuickConnectConnectionGroup extends AbstractConnectionGroup {
<ide>
<ide> /**
<ide> * The connection identifiers for this group.
|
|
Java
|
apache-2.0
|
7b84d7d7812cffb7da3ccfb40123dc43f18e594c
| 0 |
ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase,ibmsoe/hbase
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.regionserver;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CoordinatedStateManager;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValue.KVComparator;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.ScannerCallable;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
import org.apache.hadoop.hbase.regionserver.HRegion.RegionScannerImpl;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.wal.WAL;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;
/**
* Here we test to make sure that scans return the expected Results when the server is sending the
* Client heartbeat messages. Heartbeat messages are essentially keep-alive messages (they prevent
* the scanner on the client side from timing out). A heartbeat message is sent from the server to
* the client when the server has exceeded the time limit during the processing of the scan. When
* the time limit is reached, the server will return to the Client whatever Results it has
* accumulated (potentially empty).
*/
@Category(MediumTests.class)
public class TestScannerHeartbeatMessages {
final Log LOG = LogFactory.getLog(getClass());
private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static Table TABLE = null;
/**
* Table configuration
*/
private static TableName TABLE_NAME = TableName.valueOf("testScannerHeartbeatMessagesTable");
private static int NUM_ROWS = 10;
private static byte[] ROW = Bytes.toBytes("testRow");
private static byte[][] ROWS = HTestConst.makeNAscii(ROW, NUM_ROWS);
private static int NUM_FAMILIES = 3;
private static byte[] FAMILY = Bytes.toBytes("testFamily");
private static byte[][] FAMILIES = HTestConst.makeNAscii(FAMILY, NUM_FAMILIES);
private static int NUM_QUALIFIERS = 3;
private static byte[] QUALIFIER = Bytes.toBytes("testQualifier");
private static byte[][] QUALIFIERS = HTestConst.makeNAscii(QUALIFIER, NUM_QUALIFIERS);
private static int VALUE_SIZE = 128;
private static byte[] VALUE = Bytes.createMaxByteArray(VALUE_SIZE);
// Time, in milliseconds, that the client will wait for a response from the server before timing
// out. This value is used server side to determine when it is necessary to send a heartbeat
// message to the client
private static int CLIENT_TIMEOUT = 500;
// The server limits itself to running for half of the CLIENT_TIMEOUT value.
private static int SERVER_TIME_LIMIT = CLIENT_TIMEOUT / 2;
// By default, at most one row's worth of cells will be retrieved before the time limit is reached
private static int DEFAULT_ROW_SLEEP_TIME = SERVER_TIME_LIMIT / 2;
// By default, at most cells for two column families are retrieved before the time limit is
// reached
private static int DEFAULT_CF_SLEEP_TIME = SERVER_TIME_LIMIT / 2;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
((Log4JLogger) ScannerCallable.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger) HeartbeatRPCServices.LOG).getLogger().setLevel(Level.ALL);
Configuration conf = TEST_UTIL.getConfiguration();
conf.setStrings(HConstants.REGION_IMPL, HeartbeatHRegion.class.getName());
conf.setStrings(HConstants.REGION_SERVER_IMPL, HeartbeatHRegionServer.class.getName());
conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, CLIENT_TIMEOUT);
conf.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, CLIENT_TIMEOUT);
conf.setInt(HConstants.HBASE_CLIENT_PAUSE, 1);
// Check the timeout condition after every cell
conf.setLong(StoreScanner.HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK, 1);
TEST_UTIL.startMiniCluster(1);
TABLE = createTestTable(TABLE_NAME, ROWS, FAMILIES, QUALIFIERS, VALUE);
}
static Table createTestTable(TableName name, byte[][] rows, byte[][] families,
byte[][] qualifiers, byte[] cellValue) throws IOException {
Table ht = TEST_UTIL.createTable(name, families);
List<Put> puts = createPuts(rows, families, qualifiers, cellValue);
ht.put(puts);
return ht;
}
/**
* Make puts to put the input value into each combination of row, family, and qualifier
* @param rows
* @param families
* @param qualifiers
* @param value
* @return
* @throws IOException
*/
static ArrayList<Put> createPuts(byte[][] rows, byte[][] families, byte[][] qualifiers,
byte[] value) throws IOException {
Put put;
ArrayList<Put> puts = new ArrayList<>();
for (int row = 0; row < rows.length; row++) {
put = new Put(rows[row]);
for (int fam = 0; fam < families.length; fam++) {
for (int qual = 0; qual < qualifiers.length; qual++) {
KeyValue kv = new KeyValue(rows[row], families[fam], qualifiers[qual], qual, value);
put.add(kv);
}
}
puts.add(put);
}
return puts;
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
TEST_UTIL.shutdownMiniCluster();
}
@Before
public void setupBeforeTest() throws Exception {
disableSleeping();
}
@After
public void teardownAfterTest() throws Exception {
disableSleeping();
}
/**
* Test a variety of scan configurations to ensure that they return the expected Results when
* heartbeat messages are necessary. These tests are accumulated under one test case to ensure
* that they don't run in parallel. If the tests ran in parallel, they may conflict with each
* other due to changing static variables
*/
@Test
public void testScannerHeartbeatMessages() throws Exception {
testImportanceOfHeartbeats(testHeartbeatBetweenRows());
testImportanceOfHeartbeats(testHeartbeatBetweenColumnFamilies());
}
/**
* Run the test callable when heartbeats are enabled/disabled. We expect all tests to only pass
* when heartbeat messages are enabled (otherwise the test is pointless). When heartbeats are
* disabled, the test should throw an exception.
* @param testCallable
* @throws InterruptedException
*/
public void testImportanceOfHeartbeats(Callable<Void> testCallable) throws InterruptedException {
HeartbeatRPCServices.heartbeatsEnabled = true;
try {
testCallable.call();
} catch (Exception e) {
fail("Heartbeat messages are enabled, exceptions should NOT be thrown. Exception trace:"
+ ExceptionUtils.getStackTrace(e));
}
HeartbeatRPCServices.heartbeatsEnabled = false;
try {
testCallable.call();
} catch (Exception e) {
return;
} finally {
HeartbeatRPCServices.heartbeatsEnabled = true;
}
fail("Heartbeats messages are disabled, an exception should be thrown. If an exception "
+ " is not thrown, the test case is not testing the importance of heartbeat messages");
}
/**
* Test the case that the time limit for the scan is reached after each full row of cells is
* fetched.
* @throws Exception
*/
public Callable<Void> testHeartbeatBetweenRows() throws Exception {
return new Callable<Void>() {
@Override
public Void call() throws Exception {
// Configure the scan so that it can read the entire table in a single RPC. We want to test
// the case where a scan stops on the server side due to a time limit
Scan scan = new Scan();
scan.setMaxResultSize(Long.MAX_VALUE);
scan.setCaching(Integer.MAX_VALUE);
testEquivalenceOfScanWithHeartbeats(scan, DEFAULT_ROW_SLEEP_TIME, -1, false);
return null;
}
};
}
/**
* Test the case that the time limit for scans is reached in between column families
* @throws Exception
*/
public Callable<Void> testHeartbeatBetweenColumnFamilies() throws Exception {
return new Callable<Void>() {
@Override
public Void call() throws Exception {
// Configure the scan so that it can read the entire table in a single RPC. We want to test
// the case where a scan stops on the server side due to a time limit
Scan baseScan = new Scan();
baseScan.setMaxResultSize(Long.MAX_VALUE);
baseScan.setCaching(Integer.MAX_VALUE);
// Copy the scan before each test. When a scan object is used by a scanner, some of its
// fields may be changed such as start row
Scan scanCopy = new Scan(baseScan);
testEquivalenceOfScanWithHeartbeats(scanCopy, -1, DEFAULT_CF_SLEEP_TIME, false);
scanCopy = new Scan(baseScan);
testEquivalenceOfScanWithHeartbeats(scanCopy, -1, DEFAULT_CF_SLEEP_TIME, true);
return null;
}
};
}
/**
* Test the equivalence of a scan versus the same scan executed when heartbeat messages are
* necessary
* @param scan The scan configuration being tested
* @param rowSleepTime The time to sleep between fetches of row cells
* @param cfSleepTime The time to sleep between fetches of column family cells
* @param sleepBeforeCf set to true when column family sleeps should occur before the cells for
* that column family are fetched
* @throws Exception
*/
public void testEquivalenceOfScanWithHeartbeats(final Scan scan, int rowSleepTime,
int cfSleepTime, boolean sleepBeforeCf) throws Exception {
disableSleeping();
final ResultScanner scanner = TABLE.getScanner(scan);
final ResultScanner scannerWithHeartbeats = TABLE.getScanner(scan);
Result r1 = null;
Result r2 = null;
while ((r1 = scanner.next()) != null) {
// Enforce the specified sleep conditions during calls to the heartbeat scanner
configureSleepTime(rowSleepTime, cfSleepTime, sleepBeforeCf);
r2 = scannerWithHeartbeats.next();
disableSleeping();
assertTrue(r2 != null);
try {
Result.compareResults(r1, r2);
} catch (Exception e) {
fail(e.getMessage());
}
}
assertTrue(scannerWithHeartbeats.next() == null);
scanner.close();
scannerWithHeartbeats.close();
}
/**
* Helper method for setting the time to sleep between rows and column families. If a sleep time
* is negative then that sleep will be disabled
* @param rowSleepTime
* @param cfSleepTime
*/
private static void configureSleepTime(int rowSleepTime, int cfSleepTime, boolean sleepBeforeCf) {
HeartbeatHRegion.sleepBetweenRows = rowSleepTime > 0;
HeartbeatHRegion.rowSleepTime = rowSleepTime;
HeartbeatHRegion.sleepBetweenColumnFamilies = cfSleepTime > 0;
HeartbeatHRegion.columnFamilySleepTime = cfSleepTime;
HeartbeatHRegion.sleepBeforeColumnFamily = sleepBeforeCf;
}
/**
* Disable the sleeping mechanism server side.
*/
private static void disableSleeping() {
HeartbeatHRegion.sleepBetweenRows = false;
HeartbeatHRegion.sleepBetweenColumnFamilies = false;
}
/**
* Custom HRegionServer instance that instantiates {@link HeartbeatRPCServices} in place of
* {@link RSRpcServices} to allow us to toggle support for heartbeat messages
*/
private static class HeartbeatHRegionServer extends HRegionServer {
public HeartbeatHRegionServer(Configuration conf) throws IOException, InterruptedException {
super(conf);
}
public HeartbeatHRegionServer(Configuration conf, CoordinatedStateManager csm)
throws IOException, InterruptedException {
super(conf, csm);
}
@Override
protected RSRpcServices createRpcServices() throws IOException {
return new HeartbeatRPCServices(this);
}
}
/**
* Custom RSRpcServices instance that allows heartbeat support to be toggled
*/
private static class HeartbeatRPCServices extends RSRpcServices {
private static boolean heartbeatsEnabled = true;
public HeartbeatRPCServices(HRegionServer rs) throws IOException {
super(rs);
}
@Override
public ScanResponse scan(RpcController controller, ScanRequest request)
throws ServiceException {
ScanRequest.Builder builder = ScanRequest.newBuilder(request);
builder.setClientHandlesHeartbeats(heartbeatsEnabled);
return super.scan(controller, builder.build());
}
}
/**
* Custom HRegion class that instantiates {@link RegionScanner}s with configurable sleep times
* between fetches of row Results and/or column family cells. Useful for emulating an instance
* where the server is taking a long time to process a client's scan request
*/
private static class HeartbeatHRegion extends HRegion {
// Row sleeps occur AFTER each row worth of cells is retrieved.
private static int rowSleepTime = DEFAULT_ROW_SLEEP_TIME;
private static boolean sleepBetweenRows = false;
// The sleep for column families can be initiated before or after we fetch the cells for the
// column family. If the sleep occurs BEFORE then the time limits will be reached inside
// StoreScanner while we are fetching individual cells. If the sleep occurs AFTER then the time
// limit will be reached inside RegionScanner after all the cells for a column family have been
// retrieved.
private static boolean sleepBeforeColumnFamily = false;
private static int columnFamilySleepTime = DEFAULT_CF_SLEEP_TIME;
private static boolean sleepBetweenColumnFamilies = false;
public HeartbeatHRegion(Path tableDir, WAL wal, FileSystem fs, Configuration confParam,
HRegionInfo regionInfo, HTableDescriptor htd, RegionServerServices rsServices) {
super(tableDir, wal, fs, confParam, regionInfo, htd, rsServices);
}
public HeartbeatHRegion(HRegionFileSystem fs, WAL wal, Configuration confParam,
HTableDescriptor htd, RegionServerServices rsServices) {
super(fs, wal, confParam, htd, rsServices);
}
private static void columnFamilySleep() {
if (HeartbeatHRegion.sleepBetweenColumnFamilies) {
try {
Thread.sleep(HeartbeatHRegion.columnFamilySleepTime);
} catch (InterruptedException e) {
}
}
}
private static void rowSleep() {
try {
if (HeartbeatHRegion.sleepBetweenRows) {
Thread.sleep(HeartbeatHRegion.rowSleepTime);
}
} catch (InterruptedException e) {
}
}
// Instantiate the custom heartbeat region scanners
@Override
protected RegionScanner instantiateRegionScanner(Scan scan,
List<KeyValueScanner> additionalScanners) throws IOException {
if (scan.isReversed()) {
if (scan.getFilter() != null) {
scan.getFilter().setReversed(true);
}
return new HeartbeatReversedRegionScanner(scan, additionalScanners, this);
}
return new HeartbeatRegionScanner(scan, additionalScanners, this);
}
}
/**
* Custom ReversedRegionScanner that can be configured to sleep between retrievals of row Results
* and/or column family cells
*/
private static class HeartbeatReversedRegionScanner extends ReversedRegionScannerImpl {
HeartbeatReversedRegionScanner(Scan scan, List<KeyValueScanner> additionalScanners,
HRegion region) throws IOException {
super(scan, additionalScanners, region);
}
@Override
public boolean nextRaw(List<Cell> outResults, ScannerContext context)
throws IOException {
boolean moreRows = super.nextRaw(outResults, context);
HeartbeatHRegion.rowSleep();
return moreRows;
}
@Override
protected void initializeKVHeap(List<KeyValueScanner> scanners,
List<KeyValueScanner> joinedScanners, HRegion region) throws IOException {
this.storeHeap = new HeartbeatReversedKVHeap(scanners, region.getComparator());
if (!joinedScanners.isEmpty()) {
this.joinedHeap = new HeartbeatReversedKVHeap(joinedScanners, region.getComparator());
}
}
}
/**
* Custom RegionScanner that can be configured to sleep between retrievals of row Results and/or
* column family cells
*/
private static class HeartbeatRegionScanner extends RegionScannerImpl {
HeartbeatRegionScanner(Scan scan, List<KeyValueScanner> additionalScanners, HRegion region)
throws IOException {
region.super(scan, additionalScanners, region);
}
@Override
public boolean nextRaw(List<Cell> outResults, ScannerContext context)
throws IOException {
boolean moreRows = super.nextRaw(outResults, context);
HeartbeatHRegion.rowSleep();
return moreRows;
}
@Override
protected void initializeKVHeap(List<KeyValueScanner> scanners,
List<KeyValueScanner> joinedScanners, HRegion region) throws IOException {
this.storeHeap = new HeartbeatKVHeap(scanners, region.getComparator());
if (!joinedScanners.isEmpty()) {
this.joinedHeap = new HeartbeatKVHeap(joinedScanners, region.getComparator());
}
}
}
/**
* Custom KV Heap that can be configured to sleep/wait in between retrievals of column family
* cells. Useful for testing
*/
private static final class HeartbeatKVHeap extends KeyValueHeap {
public HeartbeatKVHeap(List<? extends KeyValueScanner> scanners, KVComparator comparator)
throws IOException {
super(scanners, comparator);
}
HeartbeatKVHeap(List<? extends KeyValueScanner> scanners, KVScannerComparator comparator)
throws IOException {
super(scanners, comparator);
}
@Override
public boolean next(List<Cell> result, ScannerContext context)
throws IOException {
if (HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
boolean moreRows = super.next(result, context);
if (!HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
return moreRows;
}
}
/**
* Custom reversed KV Heap that can be configured to sleep in between retrievals of column family
* cells.
*/
private static final class HeartbeatReversedKVHeap extends ReversedKeyValueHeap {
public HeartbeatReversedKVHeap(List<? extends KeyValueScanner> scanners,
KVComparator comparator) throws IOException {
super(scanners, comparator);
}
@Override
public boolean next(List<Cell> result, ScannerContext context)
throws IOException {
if (HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
boolean moreRows = super.next(result, context);
if (!HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
return moreRows;
}
}
}
|
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestScannerHeartbeatMessages.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.regionserver;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CoordinatedStateManager;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HTestConst;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValue.KVComparator;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.ScannerCallable;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
import org.apache.hadoop.hbase.regionserver.HRegion.RegionScannerImpl;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.wal.WAL;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;
/**
* Here we test to make sure that scans return the expected Results when the server is sending the
* Client heartbeat messages. Heartbeat messages are essentially keep-alive messages (they prevent
* the scanner on the client side from timing out). A heartbeat message is sent from the server to
* the client when the server has exceeded the time limit during the processing of the scan. When
* the time limit is reached, the server will return to the Client whatever Results it has
* accumulated (potentially empty).
*/
@Category(MediumTests.class)
public class TestScannerHeartbeatMessages {
final Log LOG = LogFactory.getLog(getClass());
private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static Table TABLE = null;
/**
* Table configuration
*/
private static TableName TABLE_NAME = TableName.valueOf("testScannerHeartbeatMessagesTable");
private static int NUM_ROWS = 10;
private static byte[] ROW = Bytes.toBytes("testRow");
private static byte[][] ROWS = HTestConst.makeNAscii(ROW, NUM_ROWS);
private static int NUM_FAMILIES = 3;
private static byte[] FAMILY = Bytes.toBytes("testFamily");
private static byte[][] FAMILIES = HTestConst.makeNAscii(FAMILY, NUM_FAMILIES);
private static int NUM_QUALIFIERS = 3;
private static byte[] QUALIFIER = Bytes.toBytes("testQualifier");
private static byte[][] QUALIFIERS = HTestConst.makeNAscii(QUALIFIER, NUM_QUALIFIERS);
private static int VALUE_SIZE = 128;
private static byte[] VALUE = Bytes.createMaxByteArray(VALUE_SIZE);
// Time, in milliseconds, that the client will wait for a response from the server before timing
// out. This value is used server side to determine when it is necessary to send a heartbeat
// message to the client
private static int CLIENT_TIMEOUT = 500;
// The server limits itself to running for half of the CLIENT_TIMEOUT value.
private static int SERVER_TIME_LIMIT = CLIENT_TIMEOUT / 2;
// By default, at most one row's worth of cells will be retrieved before the time limit is reached
private static int DEFAULT_ROW_SLEEP_TIME = SERVER_TIME_LIMIT / 2;
// By default, at most cells for two column families are retrieved before the time limit is
// reached
private static int DEFAULT_CF_SLEEP_TIME = SERVER_TIME_LIMIT / 2;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
((Log4JLogger) ScannerCallable.LOG).getLogger().setLevel(Level.ALL);
((Log4JLogger) HeartbeatRPCServices.LOG).getLogger().setLevel(Level.ALL);
Configuration conf = TEST_UTIL.getConfiguration();
conf.setStrings(HConstants.REGION_IMPL, HeartbeatHRegion.class.getName());
conf.setStrings(HConstants.REGION_SERVER_IMPL, HeartbeatHRegionServer.class.getName());
conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, CLIENT_TIMEOUT);
conf.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, CLIENT_TIMEOUT);
conf.setInt(HConstants.HBASE_CLIENT_PAUSE, 1);
// Check the timeout condition after every cell
conf.setLong(StoreScanner.HBASE_CELLS_SCANNED_PER_HEARTBEAT_CHECK, 1);
TEST_UTIL.startMiniCluster(1);
TABLE = createTestTable(TABLE_NAME, ROWS, FAMILIES, QUALIFIERS, VALUE);
}
static Table createTestTable(TableName name, byte[][] rows, byte[][] families,
byte[][] qualifiers, byte[] cellValue) throws IOException {
Table ht = TEST_UTIL.createTable(name, families);
List<Put> puts = createPuts(rows, families, qualifiers, cellValue);
ht.put(puts);
return ht;
}
/**
* Make puts to put the input value into each combination of row, family, and qualifier
* @param rows
* @param families
* @param qualifiers
* @param value
* @return
* @throws IOException
*/
static ArrayList<Put> createPuts(byte[][] rows, byte[][] families, byte[][] qualifiers,
byte[] value) throws IOException {
Put put;
ArrayList<Put> puts = new ArrayList<>();
for (int row = 0; row < rows.length; row++) {
put = new Put(rows[row]);
for (int fam = 0; fam < families.length; fam++) {
for (int qual = 0; qual < qualifiers.length; qual++) {
KeyValue kv = new KeyValue(rows[row], families[fam], qualifiers[qual], qual, value);
put.add(kv);
}
}
puts.add(put);
}
return puts;
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
TEST_UTIL.shutdownMiniCluster();
}
@Before
public void setupBeforeTest() throws Exception {
disableSleeping();
}
@After
public void teardownAfterTest() throws Exception {
disableSleeping();
}
/**
* Test a variety of scan configurations to ensure that they return the expected Results when
* heartbeat messages are necessary. These tests are accumulated under one test case to ensure
* that they don't run in parallel. If the tests ran in parallel, they may conflict with each
* other due to changing static variables
*/
@Test
public void testScannerHeartbeatMessages() throws Exception {
testImportanceOfHeartbeats(testHeartbeatBetweenRows());
testImportanceOfHeartbeats(testHeartbeatBetweenColumnFamilies());
}
/**
* Run the test callable when heartbeats are enabled/disabled. We expect all tests to only pass
* when heartbeat messages are enabled (otherwise the test is pointless). When heartbeats are
* disabled, the test should throw an exception.
* @param testCallable
* @throws InterruptedException
*/
public void testImportanceOfHeartbeats(Callable<Void> testCallable) throws InterruptedException {
HeartbeatRPCServices.heartbeatsEnabled = true;
try {
testCallable.call();
} catch (Exception e) {
fail("Heartbeat messages are enabled, exceptions should NOT be thrown. Exception trace:"
+ ExceptionUtils.getStackTrace(e));
}
HeartbeatRPCServices.heartbeatsEnabled = false;
try {
testCallable.call();
} catch (Exception e) {
return;
} finally {
HeartbeatRPCServices.heartbeatsEnabled = true;
}
fail("Heartbeats messages are disabled, an exception should be thrown. If an exception "
+ " is not thrown, the test case is not testing the importance of heartbeat messages");
}
/**
* Test the case that the time limit for the scan is reached after each full row of cells is
* fetched.
* @throws Exception
*/
public Callable<Void> testHeartbeatBetweenRows() throws Exception {
return new Callable<Void>() {
@Override
public Void call() throws Exception {
// Configure the scan so that it can read the entire table in a single RPC. We want to test
// the case where a scan stops on the server side due to a time limit
Scan scan = new Scan();
scan.setMaxResultSize(Long.MAX_VALUE);
scan.setCaching(Integer.MAX_VALUE);
testEquivalenceOfScanWithHeartbeats(scan, DEFAULT_ROW_SLEEP_TIME, -1, false);
return null;
}
};
}
/**
* Test the case that the time limit for scans is reached in between column families
* @throws Exception
*/
public Callable<Void> testHeartbeatBetweenColumnFamilies() throws Exception {
return new Callable<Void>() {
@Override
public Void call() throws Exception {
// Configure the scan so that it can read the entire table in a single RPC. We want to test
// the case where a scan stops on the server side due to a time limit
Scan baseScan = new Scan();
baseScan.setMaxResultSize(Long.MAX_VALUE);
baseScan.setCaching(Integer.MAX_VALUE);
// Copy the scan before each test. When a scan object is used by a scanner, some of its
// fields may be changed such as start row
Scan scanCopy = new Scan(baseScan);
testEquivalenceOfScanWithHeartbeats(scanCopy, -1, DEFAULT_CF_SLEEP_TIME, false);
scanCopy = new Scan(baseScan);
testEquivalenceOfScanWithHeartbeats(scanCopy, -1, DEFAULT_CF_SLEEP_TIME, true);
return null;
}
};
}
/**
* Test the equivalence of a scan versus the same scan executed when heartbeat messages are
* necessary
* @param scan The scan configuration being tested
* @param rowSleepTime The time to sleep between fetches of row cells
* @param cfSleepTime The time to sleep between fetches of column family cells
* @param sleepBeforeCf set to true when column family sleeps should occur before the cells for
* that column family are fetched
* @throws Exception
*/
public void testEquivalenceOfScanWithHeartbeats(final Scan scan, int rowSleepTime,
int cfSleepTime, boolean sleepBeforeCf) throws Exception {
disableSleeping();
final ResultScanner scanner = TABLE.getScanner(scan);
final ResultScanner scannerWithHeartbeats = TABLE.getScanner(scan);
Result r1 = null;
Result r2 = null;
while ((r1 = scanner.next()) != null) {
// Enforce the specified sleep conditions during calls to the heartbeat scanner
configureSleepTime(rowSleepTime, cfSleepTime, sleepBeforeCf);
r2 = scannerWithHeartbeats.next();
disableSleeping();
assertTrue(r2 != null);
try {
Result.compareResults(r1, r2);
} catch (Exception e) {
fail(e.getMessage());
}
}
assertTrue(scannerWithHeartbeats.next() == null);
scanner.close();
scannerWithHeartbeats.close();
}
/**
* Helper method for setting the time to sleep between rows and column families. If a sleep time
* is negative then that sleep will be disabled
* @param rowSleepTime
* @param cfSleepTime
*/
private static void configureSleepTime(int rowSleepTime, int cfSleepTime, boolean sleepBeforeCf) {
HeartbeatHRegion.sleepBetweenRows = rowSleepTime > 0;
HeartbeatHRegion.rowSleepTime = rowSleepTime;
HeartbeatHRegion.sleepBetweenColumnFamilies = cfSleepTime > 0;
HeartbeatHRegion.columnFamilySleepTime = cfSleepTime;
HeartbeatHRegion.sleepBeforeColumnFamily = sleepBeforeCf;
}
/**
* Disable the sleeping mechanism server side.
*/
private static void disableSleeping() {
HeartbeatHRegion.sleepBetweenRows = false;
HeartbeatHRegion.sleepBetweenColumnFamilies = false;
}
/**
* Custom HRegionServer instance that instantiates {@link HeartbeatRPCServices} in place of
* {@link RSRpcServices} to allow us to toggle support for heartbeat messages
*/
private static class HeartbeatHRegionServer extends HRegionServer {
public HeartbeatHRegionServer(Configuration conf) throws IOException, InterruptedException {
super(conf);
}
public HeartbeatHRegionServer(Configuration conf, CoordinatedStateManager csm)
throws IOException {
super(conf, csm);
}
@Override
protected RSRpcServices createRpcServices() throws IOException {
return new HeartbeatRPCServices(this);
}
}
/**
* Custom RSRpcServices instance that allows heartbeat support to be toggled
*/
private static class HeartbeatRPCServices extends RSRpcServices {
private static boolean heartbeatsEnabled = true;
public HeartbeatRPCServices(HRegionServer rs) throws IOException {
super(rs);
}
@Override
public ScanResponse scan(RpcController controller, ScanRequest request)
throws ServiceException {
ScanRequest.Builder builder = ScanRequest.newBuilder(request);
builder.setClientHandlesHeartbeats(heartbeatsEnabled);
return super.scan(controller, builder.build());
}
}
/**
* Custom HRegion class that instantiates {@link RegionScanner}s with configurable sleep times
* between fetches of row Results and/or column family cells. Useful for emulating an instance
* where the server is taking a long time to process a client's scan request
*/
private static class HeartbeatHRegion extends HRegion {
// Row sleeps occur AFTER each row worth of cells is retrieved.
private static int rowSleepTime = DEFAULT_ROW_SLEEP_TIME;
private static boolean sleepBetweenRows = false;
// The sleep for column families can be initiated before or after we fetch the cells for the
// column family. If the sleep occurs BEFORE then the time limits will be reached inside
// StoreScanner while we are fetching individual cells. If the sleep occurs AFTER then the time
// limit will be reached inside RegionScanner after all the cells for a column family have been
// retrieved.
private static boolean sleepBeforeColumnFamily = false;
private static int columnFamilySleepTime = DEFAULT_CF_SLEEP_TIME;
private static boolean sleepBetweenColumnFamilies = false;
public HeartbeatHRegion(Path tableDir, WAL wal, FileSystem fs, Configuration confParam,
HRegionInfo regionInfo, HTableDescriptor htd, RegionServerServices rsServices) {
super(tableDir, wal, fs, confParam, regionInfo, htd, rsServices);
}
public HeartbeatHRegion(HRegionFileSystem fs, WAL wal, Configuration confParam,
HTableDescriptor htd, RegionServerServices rsServices) {
super(fs, wal, confParam, htd, rsServices);
}
private static void columnFamilySleep() {
if (HeartbeatHRegion.sleepBetweenColumnFamilies) {
try {
Thread.sleep(HeartbeatHRegion.columnFamilySleepTime);
} catch (InterruptedException e) {
}
}
}
private static void rowSleep() {
try {
if (HeartbeatHRegion.sleepBetweenRows) {
Thread.sleep(HeartbeatHRegion.rowSleepTime);
}
} catch (InterruptedException e) {
}
}
// Instantiate the custom heartbeat region scanners
@Override
protected RegionScanner instantiateRegionScanner(Scan scan,
List<KeyValueScanner> additionalScanners) throws IOException {
if (scan.isReversed()) {
if (scan.getFilter() != null) {
scan.getFilter().setReversed(true);
}
return new HeartbeatReversedRegionScanner(scan, additionalScanners, this);
}
return new HeartbeatRegionScanner(scan, additionalScanners, this);
}
}
/**
* Custom ReversedRegionScanner that can be configured to sleep between retrievals of row Results
* and/or column family cells
*/
private static class HeartbeatReversedRegionScanner extends ReversedRegionScannerImpl {
HeartbeatReversedRegionScanner(Scan scan, List<KeyValueScanner> additionalScanners,
HRegion region) throws IOException {
super(scan, additionalScanners, region);
}
@Override
public boolean nextRaw(List<Cell> outResults, ScannerContext context)
throws IOException {
boolean moreRows = super.nextRaw(outResults, context);
HeartbeatHRegion.rowSleep();
return moreRows;
}
@Override
protected void initializeKVHeap(List<KeyValueScanner> scanners,
List<KeyValueScanner> joinedScanners, HRegion region) throws IOException {
this.storeHeap = new HeartbeatReversedKVHeap(scanners, region.getComparator());
if (!joinedScanners.isEmpty()) {
this.joinedHeap = new HeartbeatReversedKVHeap(joinedScanners, region.getComparator());
}
}
}
/**
* Custom RegionScanner that can be configured to sleep between retrievals of row Results and/or
* column family cells
*/
private static class HeartbeatRegionScanner extends RegionScannerImpl {
HeartbeatRegionScanner(Scan scan, List<KeyValueScanner> additionalScanners, HRegion region)
throws IOException {
region.super(scan, additionalScanners, region);
}
@Override
public boolean nextRaw(List<Cell> outResults, ScannerContext context)
throws IOException {
boolean moreRows = super.nextRaw(outResults, context);
HeartbeatHRegion.rowSleep();
return moreRows;
}
@Override
protected void initializeKVHeap(List<KeyValueScanner> scanners,
List<KeyValueScanner> joinedScanners, HRegion region) throws IOException {
this.storeHeap = new HeartbeatKVHeap(scanners, region.getComparator());
if (!joinedScanners.isEmpty()) {
this.joinedHeap = new HeartbeatKVHeap(joinedScanners, region.getComparator());
}
}
}
/**
* Custom KV Heap that can be configured to sleep/wait in between retrievals of column family
* cells. Useful for testing
*/
private static final class HeartbeatKVHeap extends KeyValueHeap {
public HeartbeatKVHeap(List<? extends KeyValueScanner> scanners, KVComparator comparator)
throws IOException {
super(scanners, comparator);
}
HeartbeatKVHeap(List<? extends KeyValueScanner> scanners, KVScannerComparator comparator)
throws IOException {
super(scanners, comparator);
}
@Override
public boolean next(List<Cell> result, ScannerContext context)
throws IOException {
if (HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
boolean moreRows = super.next(result, context);
if (!HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
return moreRows;
}
}
/**
* Custom reversed KV Heap that can be configured to sleep in between retrievals of column family
* cells.
*/
private static final class HeartbeatReversedKVHeap extends ReversedKeyValueHeap {
public HeartbeatReversedKVHeap(List<? extends KeyValueScanner> scanners,
KVComparator comparator) throws IOException {
super(scanners, comparator);
}
@Override
public boolean next(List<Cell> result, ScannerContext context)
throws IOException {
if (HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
boolean moreRows = super.next(result, context);
if (!HeartbeatHRegion.sleepBeforeColumnFamily) HeartbeatHRegion.columnFamilySleep();
return moreRows;
}
}
}
|
HBASE-13090 Addendum fixes compilation error in TestScannerHeartbeatMessages
|
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestScannerHeartbeatMessages.java
|
HBASE-13090 Addendum fixes compilation error in TestScannerHeartbeatMessages
|
<ide><path>base-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestScannerHeartbeatMessages.java
<ide> }
<ide>
<ide> public HeartbeatHRegionServer(Configuration conf, CoordinatedStateManager csm)
<del> throws IOException {
<add> throws IOException, InterruptedException {
<ide> super(conf, csm);
<ide> }
<ide>
|
|
JavaScript
|
mit
|
d0d522d523c60788f52487e01c25bcb93eb4f945
| 0 |
DanielAudino/fusebill-node
|
'use strict';
var FusebillResource = require('../FusebillResource');
var fusebillMethod = FusebillResource.method;
module.exports = FusebillResource.extend({
path: 'coupons',
includeBasic: ['create', 'list', 'update', 'retrieve', 'del'],
validate: fusebillMethod({
method: 'POST',
path: '/Validate'
}),
});
|
lib/resources/Coupons.js
|
'use strict';
module.exports = require('../FusebillResource').extend({
path: 'coupons',
includeBasic: ['create', 'list', 'update', 'retrieve', 'del'],
validate: fusebillMethod({
method: 'POST',
path: '/Validate'
}),
});
|
added validate coupon ifx
|
lib/resources/Coupons.js
|
added validate coupon ifx
|
<ide><path>ib/resources/Coupons.js
<ide> 'use strict';
<ide>
<del>module.exports = require('../FusebillResource').extend({
<add>var FusebillResource = require('../FusebillResource');
<add>var fusebillMethod = FusebillResource.method;
<add>
<add>module.exports = FusebillResource.extend({
<add>
<ide> path: 'coupons',
<ide> includeBasic: ['create', 'list', 'update', 'retrieve', 'del'],
<ide>
<ide> method: 'POST',
<ide> path: '/Validate'
<ide> }),
<add>
<ide> });
<ide>
|
|
Java
|
apache-2.0
|
18a17d787bcf69179d1bdeb015f33141d5d8486b
| 0 |
davinash/geode,deepakddixit/incubator-geode,PurelyApplied/geode,davinash/geode,deepakddixit/incubator-geode,pdxrunner/geode,shankarh/geode,smgoller/geode,masaki-yamakawa/geode,prasi-in/geode,charliemblack/geode,pdxrunner/geode,davebarnes97/geode,PurelyApplied/geode,deepakddixit/incubator-geode,davinash/geode,masaki-yamakawa/geode,prasi-in/geode,smanvi-pivotal/geode,deepakddixit/incubator-geode,pdxrunner/geode,davebarnes97/geode,pdxrunner/geode,smgoller/geode,PurelyApplied/geode,deepakddixit/incubator-geode,pivotal-amurmann/geode,deepakddixit/incubator-geode,pivotal-amurmann/geode,smgoller/geode,charliemblack/geode,charliemblack/geode,prasi-in/geode,shankarh/geode,charliemblack/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,davebarnes97/geode,masaki-yamakawa/geode,davinash/geode,pivotal-amurmann/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,deepakddixit/incubator-geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,davebarnes97/geode,smgoller/geode,davebarnes97/geode,smgoller/geode,prasi-in/geode,smanvi-pivotal/geode,shankarh/geode,smgoller/geode,pdxrunner/geode,masaki-yamakawa/geode,PurelyApplied/geode,shankarh/geode,smgoller/geode,masaki-yamakawa/geode,shankarh/geode,davinash/geode,pdxrunner/geode,masaki-yamakawa/geode,pivotal-amurmann/geode,pivotal-amurmann/geode,davinash/geode,prasi-in/geode,smanvi-pivotal/geode,PurelyApplied/geode,smanvi-pivotal/geode,smanvi-pivotal/geode,PurelyApplied/geode,charliemblack/geode,PurelyApplied/geode,davebarnes97/geode,davinash/geode,jdeppe-pivotal/geode,pdxrunner/geode,jdeppe-pivotal/geode,davebarnes97/geode
|
/*
* 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 dunit;
import java.io.File;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.experimental.categories.Category;
import org.springframework.data.gemfire.support.GemfireCache;
import junit.framework.TestCase;
import com.gemstone.gemfire.InternalGemFireError;
import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.SystemFailure;
import com.gemstone.gemfire.admin.internal.AdminDistributedSystemImpl;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.DiskStoreFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.hdfs.internal.HDFSStoreImpl;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HoplogConfig;
import com.gemstone.gemfire.cache.query.QueryTestUtils;
import com.gemstone.gemfire.cache.query.internal.QueryObserverHolder;
import com.gemstone.gemfire.cache30.ClientServerTestCase;
import com.gemstone.gemfire.cache30.GlobalLockingDUnitTest;
import com.gemstone.gemfire.cache30.MultiVMRegionTestCase;
import com.gemstone.gemfire.cache30.RegionTestCase;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.distributed.Locator;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.DistributionConfigImpl;
import com.gemstone.gemfire.distributed.internal.DistributionMessageObserver;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem.CreationStackGenerator;
import com.gemstone.gemfire.distributed.internal.membership.gms.MembershipManagerHelper;
import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.internal.InternalDataSerializer;
import com.gemstone.gemfire.internal.InternalInstantiator;
import com.gemstone.gemfire.internal.OSProcess;
import com.gemstone.gemfire.internal.SocketCreator;
import com.gemstone.gemfire.internal.admin.ClientStatsManager;
import com.gemstone.gemfire.internal.cache.DiskStoreObserver;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.HARegion;
import com.gemstone.gemfire.internal.cache.InitialImageOperation;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.tier.InternalClientMembership;
import com.gemstone.gemfire.internal.cache.tier.sockets.CacheServerTestUtil;
import com.gemstone.gemfire.internal.cache.tier.sockets.ClientProxyMembershipID;
import com.gemstone.gemfire.internal.cache.tier.sockets.DataSerializerPropogationDUnitTest;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheCreation;
import com.gemstone.gemfire.internal.logging.InternalLogWriter;
import com.gemstone.gemfire.internal.logging.LocalLogWriter;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.internal.logging.LogWriterFactory;
import com.gemstone.gemfire.internal.logging.LogWriterImpl;
import com.gemstone.gemfire.internal.logging.ManagerLogWriter;
import com.gemstone.gemfire.internal.logging.log4j.LogWriterLogger;
import com.gemstone.gemfire.management.internal.cli.LogWrapper;
import com.gemstone.gemfire.test.junit.categories.DistributedTest;
import com.gemstone.gemfire.test.dunit.standalone.DUnitLauncher;
/**
* This class is the superclass of all distributed unit tests.
*
* tests/hydra/JUnitTestTask is the main DUnit driver. It supports two
* additional public static methods if they are defined in the test case:
*
* public static void caseSetUp() -- comparable to JUnit's BeforeClass annotation
*
* public static void caseTearDown() -- comparable to JUnit's AfterClass annotation
*
* @author David Whitlock
*/
@Category(DistributedTest.class)
@SuppressWarnings("serial")
public abstract class DistributedTestCase extends TestCase implements java.io.Serializable {
private static final Logger logger = LogService.getLogger();
private static final LogWriterLogger oldLogger = LogWriterLogger.create(logger);
private static final LinkedHashSet<String> testHistory = new LinkedHashSet<String>();
private static void setUpCreationStackGenerator() {
// the following is moved from InternalDistributedSystem to fix #51058
InternalDistributedSystem.TEST_CREATION_STACK_GENERATOR.set(
new CreationStackGenerator() {
@Override
public Throwable generateCreationStack(final DistributionConfig config) {
final StringBuilder sb = new StringBuilder();
final String[] validAttributeNames = config.getAttributeNames();
for (int i = 0; i < validAttributeNames.length; i++) {
final String attName = validAttributeNames[i];
final Object actualAtt = config.getAttributeObject(attName);
String actualAttStr = actualAtt.toString();
sb.append(" ");
sb.append(attName);
sb.append("=\"");
if (actualAtt.getClass().isArray()) {
actualAttStr = InternalDistributedSystem.arrayToString(actualAtt);
}
sb.append(actualAttStr);
sb.append("\"");
sb.append("\n");
}
return new Throwable("Creating distributed system with the following configuration:\n" + sb.toString());
}
});
}
private static void tearDownCreationStackGenerator() {
InternalDistributedSystem.TEST_CREATION_STACK_GENERATOR.set(InternalDistributedSystem.DEFAULT_CREATION_STACK_GENERATOR);
}
/** This VM's connection to the distributed system */
public static InternalDistributedSystem system;
private static Class lastSystemCreatedInTest;
private static Properties lastSystemProperties;
public static volatile String testName;
private static ConcurrentLinkedQueue<ExpectedException> expectedExceptions = new ConcurrentLinkedQueue<ExpectedException>();
/** For formatting timing info */
private static final DecimalFormat format = new DecimalFormat("###.###");
public static boolean reconnect = false;
public static final boolean logPerTest = Boolean.getBoolean("dunitLogPerTest");
/////////////////////// Utility Methods ///////////////////////
public void attachDebugger(VM vm, final String msg) {
vm.invoke(new SerializableRunnable("Attach Debugger") {
public void run() {
com.gemstone.gemfire.internal.util.DebuggerSupport.
waitForJavaDebugger(getSystem().getLogWriter().convertToLogWriterI18n(), msg);
}
});
}
/**
* Invokes a <code>SerializableRunnable</code> in every VM that
* DUnit knows about.
*
* @see VM#invoke(Runnable)
*/
public static void invokeInEveryVM(SerializableRunnable work) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invoke(work);
}
}
}
public static void invokeInLocator(SerializableRunnable work) {
Host.getLocator().invoke(work);
}
/**
* Invokes a <code>SerializableCallable</code> in every VM that
* DUnit knows about.
*
* @return a Map of results, where the key is the VM and the value is the result
* @see VM#invoke(Callable)
*/
protected static Map invokeInEveryVM(SerializableCallable work) {
HashMap ret = new HashMap();
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
ret.put(vm, vm.invoke(work));
}
}
return ret;
}
/**
* Invokes a method in every remote VM that DUnit knows about.
*
* @see VM#invoke(Class, String)
*/
protected static void invokeInEveryVM(Class c, String method) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invoke(c, method);
}
}
}
/**
* Invokes a method in every remote VM that DUnit knows about.
*
* @see VM#invoke(Class, String)
*/
protected static void invokeInEveryVM(Class c, String method, Object[] methodArgs) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invoke(c, method, methodArgs);
}
}
}
/**
* The number of milliseconds to try repeating validation code in the
* event that AssertionFailedError is thrown. For ACK scopes, no
* repeat should be necessary.
*/
protected long getRepeatTimeoutMs() {
return 0;
}
protected void invokeRepeatingIfNecessary(VM vm, RepeatableRunnable task) {
vm.invokeRepeatingIfNecessary(task, getRepeatTimeoutMs());
}
/**
* Invokes a <code>SerializableRunnable</code> in every VM that
* DUnit knows about. If work.run() throws an assertion failure,
* its execution is repeated, until no assertion failure occurs or
* repeatTimeout milliseconds have passed.
*
* @see VM#invoke(Runnable)
*/
protected void invokeInEveryVMRepeatingIfNecessary(RepeatableRunnable work) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invokeRepeatingIfNecessary(work, getRepeatTimeoutMs());
}
}
}
/** Return the total number of VMs on all hosts */
protected static int getVMCount() {
int count = 0;
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
count += host.getVMCount();
}
return count;
}
/** print a stack dump for this vm
@author bruce
@since 5.0
*/
public static void dumpStack() {
com.gemstone.gemfire.internal.OSProcess.printStacks(0, false);
}
/** print a stack dump for the given vm
@author bruce
@since 5.0
*/
public static void dumpStack(VM vm) {
vm.invoke(dunit.DistributedTestCase.class, "dumpStack");
}
/** print stack dumps for all vms on the given host
@author bruce
@since 5.0
*/
public static void dumpStack(Host host) {
for (int v=0; v < host.getVMCount(); v++) {
host.getVM(v).invoke(dunit.DistributedTestCase.class, "dumpStack");
}
}
/** print stack dumps for all vms
@author bruce
@since 5.0
*/
public static void dumpAllStacks() {
for (int h=0; h < Host.getHostCount(); h++) {
dumpStack(Host.getHost(h));
}
}
public static String noteTiming(long operations, String operationUnit,
long beginTime, long endTime,
String timeUnit)
{
long delta = endTime - beginTime;
StringBuffer sb = new StringBuffer();
sb.append(" Performed ");
sb.append(operations);
sb.append(" ");
sb.append(operationUnit);
sb.append(" in ");
sb.append(delta);
sb.append(" ");
sb.append(timeUnit);
sb.append("\n");
double ratio = ((double) operations) / ((double) delta);
sb.append(" ");
sb.append(format.format(ratio));
sb.append(" ");
sb.append(operationUnit);
sb.append(" per ");
sb.append(timeUnit);
sb.append("\n");
ratio = ((double) delta) / ((double) operations);
sb.append(" ");
sb.append(format.format(ratio));
sb.append(" ");
sb.append(timeUnit);
sb.append(" per ");
sb.append(operationUnit);
sb.append("\n");
return sb.toString();
}
/**
* Creates a new LogWriter and adds it to the config properties. The config
* can then be used to connect to DistributedSystem, thus providing early
* access to the LogWriter before connecting. This call does not connect
* to the DistributedSystem. It simply creates and returns the LogWriter
* that will eventually be used by the DistributedSystem that connects using
* config.
*
* @param config the DistributedSystem config properties to add LogWriter to
* @return early access to the DistributedSystem LogWriter
*/
protected static LogWriter createLogWriter(Properties config) { // TODO:LOG:CONVERT: this is being used for ExpectedExceptions
Properties nonDefault = config;
if (nonDefault == null) {
nonDefault = new Properties();
}
addHydraProperties(nonDefault);
DistributionConfig dc = new DistributionConfigImpl(nonDefault);
LogWriter logger = LogWriterFactory.createLogWriterLogger(
false/*isLoner*/, false/*isSecurityLog*/, dc,
false);
// if config was non-null, then these will be added to it...
nonDefault.put(DistributionConfig.LOG_WRITER_NAME, logger);
return logger;
}
/**
* Fetches the GemFireDescription for this test and adds its
* DistributedSystem properties to the provided props parameter.
*
* @param config the properties to add hydra's test properties to
*/
protected static void addHydraProperties(Properties config) {
Properties p = DUnitEnv.get().getDistributedSystemProperties();
for (Iterator iter = p.entrySet().iterator();
iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (config.getProperty(key) == null) {
config.setProperty(key, value);
}
}
}
//////////////////////// Constructors ////////////////////////
/**
* Creates a new <code>DistributedTestCase</code> test with the
* given name.
*/
public DistributedTestCase(String name) {
super(name);
DUnitLauncher.launchIfNeeded();
}
/////////////////////// Instance Methods ///////////////////////
protected Class getTestClass() {
Class clazz = getClass();
while (clazz.getDeclaringClass() != null) {
clazz = clazz.getDeclaringClass();
}
return clazz;
}
/**
* This finds the log level configured for the test run. It should be used
* when creating a new distributed system if you want to specify a log level.
* @return the dunit log-level setting
*/
public static String getDUnitLogLevel() {
Properties p = DUnitEnv.get().getDistributedSystemProperties();
String result = p.getProperty(DistributionConfig.LOG_LEVEL_NAME);
if (result == null) {
result = ManagerLogWriter.levelToString(DistributionConfig.DEFAULT_LOG_LEVEL);
}
return result;
}
public final static Properties getAllDistributedSystemProperties(Properties props) {
Properties p = DUnitEnv.get().getDistributedSystemProperties();
// our tests do not expect auto-reconnect to be on by default
if (!p.contains(DistributionConfig.DISABLE_AUTO_RECONNECT_NAME)) {
p.put(DistributionConfig.DISABLE_AUTO_RECONNECT_NAME, "true");
}
for (Iterator iter = props.entrySet().iterator();
iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
Object value = entry.getValue();
p.put(key, value);
}
return p;
}
public void setSystem(Properties props, DistributedSystem ds) {
system = (InternalDistributedSystem)ds;
lastSystemProperties = props;
lastSystemCreatedInTest = getTestClass();
}
/**
* Returns this VM's connection to the distributed system. If
* necessary, the connection will be lazily created using the given
* <code>Properties</code>. Note that this method uses hydra's
* configuration to determine the location of log files, etc.
* Note: "final" was removed so that WANTestBase can override this method.
* This was part of the xd offheap merge.
*
* @see hydra.DistributedConnectionMgr#connect
* @since 3.0
*/
public /*final*/ InternalDistributedSystem getSystem(Properties props) {
// Setting the default disk store name is now done in setUp
if (system == null) {
system = InternalDistributedSystem.getAnyInstance();
}
if (system == null || !system.isConnected()) {
// Figure out our distributed system properties
Properties p = getAllDistributedSystemProperties(props);
lastSystemCreatedInTest = getTestClass();
if (logPerTest) {
String testMethod = getTestName();
String testName = lastSystemCreatedInTest.getName() + '-' + testMethod;
String oldLogFile = p.getProperty(DistributionConfig.LOG_FILE_NAME);
p.put(DistributionConfig.LOG_FILE_NAME,
oldLogFile.replace("system.log", testName+".log"));
String oldStatFile = p.getProperty(DistributionConfig.STATISTIC_ARCHIVE_FILE_NAME);
p.put(DistributionConfig.STATISTIC_ARCHIVE_FILE_NAME,
oldStatFile.replace("statArchive.gfs", testName+".gfs"));
}
system = (InternalDistributedSystem)DistributedSystem.connect(p);
lastSystemProperties = p;
} else {
boolean needNewSystem = false;
if(!getTestClass().equals(lastSystemCreatedInTest)) {
Properties newProps = getAllDistributedSystemProperties(props);
needNewSystem = !newProps.equals(lastSystemProperties);
if(needNewSystem) {
getLogWriter().info(
"Test class has changed and the new DS properties are not an exact match. "
+ "Forcing DS disconnect. Old props = "
+ lastSystemProperties + "new props=" + newProps);
}
} else {
Properties activeProps = system.getProperties();
for (Iterator iter = props.entrySet().iterator();
iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (!value.equals(activeProps.getProperty(key))) {
needNewSystem = true;
getLogWriter().info("Forcing DS disconnect. For property " + key
+ " old value = " + activeProps.getProperty(key)
+ " new value = " + value);
break;
}
}
}
if(needNewSystem) {
// the current system does not meet our needs to disconnect and
// call recursively to get a new system.
getLogWriter().info("Disconnecting from current DS in order to make a new one");
disconnectFromDS();
getSystem(props);
}
}
return system;
}
/**
* Crash the cache in the given VM in such a way that it immediately stops communicating with
* peers. This forces the VM's membership manager to throw a ForcedDisconnectException by
* forcibly terminating the JGroups protocol stack with a fake EXIT event.<p>
*
* NOTE: if you use this method be sure that you clean up the VM before the end of your
* test with disconnectFromDS() or disconnectAllFromDS().
*/
public boolean crashDistributedSystem(VM vm) {
return (Boolean)vm.invoke(new SerializableCallable("crash distributed system") {
public Object call() throws Exception {
DistributedSystem msys = InternalDistributedSystem.getAnyInstance();
crashDistributedSystem(msys);
return true;
}
});
}
/**
* Crash the cache in the given VM in such a way that it immediately stops communicating with
* peers. This forces the VM's membership manager to throw a ForcedDisconnectException by
* forcibly terminating the JGroups protocol stack with a fake EXIT event.<p>
*
* NOTE: if you use this method be sure that you clean up the VM before the end of your
* test with disconnectFromDS() or disconnectAllFromDS().
*/
public void crashDistributedSystem(final DistributedSystem msys) {
MembershipManagerHelper.crashDistributedSystem(msys);
MembershipManagerHelper.inhibitForcedDisconnectLogging(false);
WaitCriterion wc = new WaitCriterion() {
public boolean done() {
return !msys.isConnected();
}
public String description() {
return "waiting for distributed system to finish disconnecting: " + msys;
}
};
// try {
waitForCriterion(wc, 10000, 1000, true);
// } finally {
// dumpMyThreads(getLogWriter());
// }
}
private String getDefaultDiskStoreName() {
String vmid = System.getProperty("vmid");
return "DiskStore-" + vmid + "-"+ getTestClass().getCanonicalName() + "." + getTestName();
}
/**
* Returns this VM's connection to the distributed system. If
* necessary, the connection will be lazily created using the
* <code>Properties</code> returned by {@link
* #getDistributedSystemProperties}.
*
* @see #getSystem(Properties)
*
* @since 3.0
*/
public final InternalDistributedSystem getSystem() {
return getSystem(this.getDistributedSystemProperties());
}
/**
* Returns a loner distributed system that isn't connected to other
* vms
*
* @since 6.5
*/
public final InternalDistributedSystem getLonerSystem() {
Properties props = this.getDistributedSystemProperties();
props.put(DistributionConfig.MCAST_PORT_NAME, "0");
props.put(DistributionConfig.LOCATORS_NAME, "");
return getSystem(props);
}
/**
* Returns a loner distributed system in combination with enforceUniqueHost
* and redundancyZone properties.
* Added specifically to test scenario of defect #47181.
*/
public final InternalDistributedSystem getLonerSystemWithEnforceUniqueHost() {
Properties props = this.getDistributedSystemProperties();
props.put(DistributionConfig.MCAST_PORT_NAME, "0");
props.put(DistributionConfig.LOCATORS_NAME, "");
props.put(DistributionConfig.ENFORCE_UNIQUE_HOST_NAME, "true");
props.put(DistributionConfig.REDUNDANCY_ZONE_NAME, "zone1");
return getSystem(props);
}
/**
* Returns whether or this VM is connected to a {@link
* DistributedSystem}.
*/
public final boolean isConnectedToDS() {
return system != null && system.isConnected();
}
/**
* Returns a <code>Properties</code> object used to configure a
* connection to a {@link
* com.gemstone.gemfire.distributed.DistributedSystem}.
* Unless overridden, this method will return an empty
* <code>Properties</code> object.
*
* @since 3.0
*/
public Properties getDistributedSystemProperties() {
return new Properties();
}
/**
* Sets up the test (noop).
*/
@Override
public void setUp() throws Exception {
logTestHistory();
setUpCreationStackGenerator();
testName = getName();
System.setProperty(HoplogConfig.ALLOW_LOCAL_HDFS_PROP, "true");
if (testName != null) {
GemFireCacheImpl.setDefaultDiskStoreName(getDefaultDiskStoreName());
String baseDefaultDiskStoreName = getTestClass().getCanonicalName() + "." + getTestName();
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
String vmDefaultDiskStoreName = "DiskStore-" + h + "-" + v + "-" + baseDefaultDiskStoreName;
vm.invoke(DistributedTestCase.class, "perVMSetUp", new Object[] {testName, vmDefaultDiskStoreName});
}
}
}
System.out.println("\n\n[setup] START TEST " + getClass().getSimpleName()+"."+testName+"\n\n");
}
/**
* Write a message to the log about what tests have ran previously. This
* makes it easier to figure out if a previous test may have caused problems
*/
private void logTestHistory() {
String classname = getClass().getSimpleName();
testHistory.add(classname);
System.out.println("Previously run tests: " + testHistory);
}
public static void perVMSetUp(String name, String defaultDiskStoreName) {
setTestName(name);
GemFireCacheImpl.setDefaultDiskStoreName(defaultDiskStoreName);
System.setProperty(HoplogConfig.ALLOW_LOCAL_HDFS_PROP, "true");
}
public static void setTestName(String name) {
testName = name;
}
public static String getTestName() {
return testName;
}
/**
* For logPerTest to work, we have to disconnect from the DS, but all
* subclasses do not call super.tearDown(). To prevent this scenario
* this method has been declared final. Subclasses must now override
* {@link #tearDown2()} instead.
* @throws Exception
*/
@Override
public final void tearDown() throws Exception {
tearDownCreationStackGenerator();
tearDown2();
realTearDown();
tearDownAfter();
}
/**
* Tears down the test. This method is called by the final {@link #tearDown()} method and should be overridden to
* perform actual test cleanup and release resources used by the test. The tasks executed by this method are
* performed before the DUnit test framework using Hydra cleans up the client VMs.
* <p/>
* @throws Exception if the tear down process and test cleanup fails.
* @see #tearDown
* @see #tearDownAfter()
*/
// TODO rename this method to tearDownBefore and change the access modifier to protected!
public void tearDown2() throws Exception {
}
protected void realTearDown() throws Exception {
if (logPerTest) {
disconnectFromDS();
invokeInEveryVM(DistributedTestCase.class, "disconnectFromDS");
}
cleanupAllVms();
}
/**
* Tears down the test. Performs additional tear down tasks after the DUnit tests framework using Hydra cleans up
* the client VMs. This method is called by the final {@link #tearDown()} method and should be overridden to perform
* post tear down activities.
* <p/>
* @throws Exception if the test tear down process fails.
* @see #tearDown()
* @see #tearDown2()
*/
protected void tearDownAfter() throws Exception {
}
public static void cleanupAllVms()
{
cleanupThisVM();
invokeInEveryVM(DistributedTestCase.class, "cleanupThisVM");
invokeInLocator(new SerializableRunnable() {
public void run() {
DistributionMessageObserver.setInstance(null);
unregisterInstantiatorsInThisVM();
}
});
DUnitLauncher.closeAndCheckForSuspects();
}
private static void cleanupThisVM() {
closeCache();
SocketCreator.resolve_dns = true;
CacheCreation.clearThreadLocals();
System.getProperties().remove("gemfire.log-level");
System.getProperties().remove("jgroups.resolve_dns");
InitialImageOperation.slowImageProcessing = 0;
DistributionMessageObserver.setInstance(null);
QueryTestUtils.setCache(null);
CacheServerTestUtil.clearCacheReference();
RegionTestCase.preSnapshotRegion = null;
GlobalLockingDUnitTest.region_testBug32356 = null;
LogWrapper.close();
ClientProxyMembershipID.system = null;
MultiVMRegionTestCase.CCRegion = null;
InternalClientMembership.unregisterAllListeners();
ClientStatsManager.cleanupForTests();
ClientServerTestCase.AUTO_LOAD_BALANCE = false;
unregisterInstantiatorsInThisVM();
DistributionMessageObserver.setInstance(null);
QueryObserverHolder.reset();
DiskStoreObserver.setInstance(null);
System.getProperties().remove("gemfire.log-level");
System.getProperties().remove("jgroups.resolve_dns");
if (InternalDistributedSystem.systemAttemptingReconnect != null) {
InternalDistributedSystem.systemAttemptingReconnect.stopReconnecting();
}
ExpectedException ex;
while((ex = expectedExceptions.poll()) != null) {
ex.remove();
}
}
private static void closeCache() {
GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
if(cache != null && !cache.isClosed()) {
destroyRegions(cache);
cache.close();
}
}
protected static final void destroyRegions(Cache cache)
throws InternalGemFireError, Error, VirtualMachineError {
if (cache != null && !cache.isClosed()) {
//try to destroy the root regions first so that
//we clean up any persistent files.
for (Iterator itr = cache.rootRegions().iterator(); itr.hasNext();) {
Region root = (Region)itr.next();
//for colocated regions you can't locally destroy a partitioned
//region.
if(root.isDestroyed() || root instanceof HARegion || root instanceof PartitionedRegion) {
continue;
}
try {
root.localDestroyRegion("teardown");
}
catch (VirtualMachineError e) {
SystemFailure.initiateFailure(e);
throw e;
}
catch (Throwable t) {
getLogWriter().error(t);
}
}
}
}
public static void unregisterAllDataSerializersFromAllVms()
{
unregisterDataSerializerInThisVM();
invokeInEveryVM(new SerializableRunnable() {
public void run() {
unregisterDataSerializerInThisVM();
}
});
invokeInLocator(new SerializableRunnable() {
public void run() {
unregisterDataSerializerInThisVM();
}
});
}
public static void unregisterInstantiatorsInThisVM() {
// unregister all the instantiators
InternalInstantiator.reinitialize();
assertEquals(0, InternalInstantiator.getInstantiators().length);
}
public static void unregisterDataSerializerInThisVM()
{
DataSerializerPropogationDUnitTest.successfullyLoadedTestDataSerializer = false;
// unregister all the Dataserializers
InternalDataSerializer.reinitialize();
// ensure that all are unregistered
assertEquals(0, InternalDataSerializer.getSerializers().length);
}
protected static void disconnectAllFromDS() {
disconnectFromDS();
invokeInEveryVM(DistributedTestCase.class,
"disconnectFromDS");
}
/**
* Disconnects this VM from the distributed system
*/
public static void disconnectFromDS() {
testName = null;
GemFireCacheImpl.testCacheXml = null;
if (system != null) {
system.disconnect();
system = null;
}
for (;;) {
DistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
if (ds == null) {
break;
}
try {
ds.disconnect();
}
catch (Exception e) {
// ignore
}
}
{
AdminDistributedSystemImpl ads =
AdminDistributedSystemImpl.getConnectedInstance();
if (ads != null) {// && ads.isConnected()) {
ads.disconnect();
}
}
}
/**
* Strip the package off and gives just the class name.
* Needed because of Windows file name limits.
*/
private String getShortClassName() {
String result = this.getClass().getName();
int idx = result.lastIndexOf('.');
if (idx != -1) {
result = result.substring(idx+1);
}
return result;
}
/** get the host name to use for a server cache in client/server dunit
* testing
* @param host
* @return the host name
*/
public static String getServerHostName(Host host) {
return System.getProperty("gemfire.server-bind-address") != null?
System.getProperty("gemfire.server-bind-address")
: host.getHostName();
}
/** get the IP literal name for the current host, use this instead of
* "localhost" to avoid IPv6 name resolution bugs in the JDK/machine config.
* @return an ip literal, this method honors java.net.preferIPvAddresses
*/
public static String getIPLiteral() {
try {
return SocketCreator.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new Error("problem determining host IP address", e);
}
}
/**
* Get the port that the standard dunit locator is listening on.
* @return
*/
public static int getDUnitLocatorPort() {
return DUnitEnv.get().getLocatorPort();
}
/**
* Returns a unique name for this test method. It is based on the
* name of the class as well as the name of the method.
*/
public String getUniqueName() {
return getShortClassName() + "_" + this.getName();
}
/**
* Returns a <code>LogWriter</code> for logging information
* @deprecated Use a static logger from the log4j2 LogService.getLogger instead.
*/
@Deprecated
public static InternalLogWriter getLogWriter() {
return oldLogger;
}
/**
* Helper method that causes this test to fail because of the given
* exception.
*/
public static void fail(String message, Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
pw.print(message);
pw.print(": ");
ex.printStackTrace(pw);
fail(sw.toString());
}
// utility methods
/** pause for a default interval */
protected void pause() {
pause(250);
}
/**
* Use of this function indicates a place in the tests tree where t
* he use of Thread.sleep() is
* highly questionable.
* <p>
* Some places in the system, especially those that test expirations and other
* timeouts, have a very good reason to call {@link Thread#sleep(long)}. The
* <em>other</em> places are marked by the use of this method.
*
* @param ms
*/
static public final void staticPause(int ms) {
// getLogWriter().info("FIXME: Pausing for " + ms + " ms..."/*, new Exception()*/);
final long target = System.currentTimeMillis() + ms;
try {
for (;;) {
long msLeft = target - System.currentTimeMillis();
if (msLeft <= 0) {
break;
}
Thread.sleep(msLeft);
}
}
catch (InterruptedException e) {
fail("interrupted", e);
}
}
/**
* Blocks until the clock used for expiration moves forward.
* @return the last time stamp observed
*/
public static final long waitForExpiryClockToChange(LocalRegion lr) {
return waitForExpiryClockToChange(lr, lr.cacheTimeMillis());
}
/**
* Blocks until the clock used for expiration moves forward.
* @param baseTime the timestamp that the clock must exceed
* @return the last time stamp observed
*/
public static final long waitForExpiryClockToChange(LocalRegion lr, final long baseTime) {
long nowTime;
do {
Thread.yield();
nowTime = lr.cacheTimeMillis();
} while ((nowTime - baseTime) <= 0L);
return nowTime;
}
/** pause for specified ms interval
* Make sure system clock has advanced by the specified number of millis before
* returning.
*/
public static final void pause(int ms) {
LogWriter log = getLogWriter();
if (ms >= 1000 || log.fineEnabled()) { // check for fine but log at info
getLogWriter().info("Pausing for " + ms + " ms..."/*, new Exception()*/);
}
final long target = System.currentTimeMillis() + ms;
try {
for (;;) {
long msLeft = target - System.currentTimeMillis();
if (msLeft <= 0) {
break;
}
Thread.sleep(msLeft);
}
}
catch (InterruptedException e) {
fail("interrupted", e);
}
}
public interface WaitCriterion {
public boolean done();
public String description();
}
public interface WaitCriterion2 extends WaitCriterion {
/**
* If this method returns true then quit waiting even if we are not done.
* This allows a wait to fail early.
*/
public boolean stopWaiting();
}
/**
* If true, we randomize the amount of time we wait before polling a
* {@link WaitCriterion}.
*/
static private final boolean USE_JITTER = true;
static private final Random jitter = new Random();
/**
* Return a jittered interval up to a maximum of <code>ms</code>
* milliseconds, inclusive.
*
* The result is bounded by 50 ms as a minimum and 5000 ms as a maximum.
*
* @param ms total amount of time to wait
* @return randomized interval we should wait
*/
private static int jitterInterval(long ms) {
final int minLegal = 50;
final int maxLegal = 5000;
if (ms <= minLegal) {
return (int)ms; // Don't ever jitter anything below this.
}
int maxReturn = maxLegal;
if (ms < maxLegal) {
maxReturn = (int)ms;
}
return minLegal + jitter.nextInt(maxReturn - minLegal + 1);
}
/**
* Wait until given criterion is met
* @param ev criterion to wait on
* @param ms total time to wait, in milliseconds
* @param interval pause interval between waits
* @param throwOnTimeout if false, don't generate an error
*/
static public void waitForCriterion(WaitCriterion ev, long ms,
long interval, boolean throwOnTimeout) {
long waitThisTime;
if (USE_JITTER) {
waitThisTime = jitterInterval(interval);
}
else {
waitThisTime = interval;
}
final long tilt = System.currentTimeMillis() + ms;
for (;;) {
// getLogWriter().info("Testing to see if event has occurred: " + ev.description());
if (ev.done()) {
return; // success
}
if (ev instanceof WaitCriterion2) {
WaitCriterion2 ev2 = (WaitCriterion2)ev;
if (ev2.stopWaiting()) {
if (throwOnTimeout) {
fail("stopWaiting returned true: " + ev.description());
}
return;
}
}
// Calculate time left
long timeLeft = tilt - System.currentTimeMillis();
if (timeLeft <= 0) {
if (!throwOnTimeout) {
return; // not an error, but we're done
}
fail("Event never occurred after " + ms + " ms: " + ev.description());
}
if (waitThisTime > timeLeft) {
waitThisTime = timeLeft;
}
// Wait a little bit
Thread.yield();
try {
// getLogWriter().info("waiting " + waitThisTime + "ms for " + ev.description());
Thread.sleep(waitThisTime);
} catch (InterruptedException e) {
fail("interrupted");
}
}
}
/**
* Wait on a mutex. This is done in a loop in order to address the
* "spurious wakeup" "feature" in Java.
* @param ev condition to test
* @param mutex object to lock and wait on
* @param ms total amount of time to wait
* @param interval interval to pause for the wait
* @param throwOnTimeout if false, no error is thrown.
*/
static public void waitMutex(WaitCriterion ev, Object mutex, long ms,
long interval, boolean throwOnTimeout) {
final long tilt = System.currentTimeMillis() + ms;
long waitThisTime;
if (USE_JITTER) {
waitThisTime = jitterInterval(interval);
}
else {
waitThisTime = interval;
}
synchronized (mutex) {
for (;;) {
if (ev.done()) {
break;
}
long timeLeft = tilt - System.currentTimeMillis();
if (timeLeft <= 0) {
if (!throwOnTimeout) {
return; // not an error, but we're done
}
fail("Event never occurred after " + ms + " ms: " + ev.description());
}
if (waitThisTime > timeLeft) {
waitThisTime = timeLeft;
}
try {
mutex.wait(waitThisTime);
} catch (InterruptedException e) {
fail("interrupted");
}
} // for
} // synchronized
}
/**
* Wait for a thread to join
* @param t thread to wait on
* @param ms maximum time to wait
* @throws AssertionFailure if the thread does not terminate
*/
static public void join(Thread t, long ms, LogWriter logger) {
final long tilt = System.currentTimeMillis() + ms;
final long incrementalWait;
if (USE_JITTER) {
incrementalWait = jitterInterval(ms);
}
else {
incrementalWait = ms; // wait entire time, no looping.
}
final long start = System.currentTimeMillis();
for (;;) {
// I really do *not* understand why this check is necessary
// but it is, at least with JDK 1.6. According to the source code
// and the javadocs, one would think that join() would exit immediately
// if the thread is dead. However, I can tell you from experimentation
// that this is not the case. :-( djp 2008-12-08
if (!t.isAlive()) {
break;
}
try {
t.join(incrementalWait);
} catch (InterruptedException e) {
fail("interrupted");
}
if (System.currentTimeMillis() >= tilt) {
break;
}
} // for
if (logger == null) {
logger = new LocalLogWriter(LogWriterImpl.INFO_LEVEL, System.out);
}
if (t.isAlive()) {
logger.info("HUNG THREAD");
dumpStackTrace(t, t.getStackTrace(), logger);
dumpMyThreads(logger);
t.interrupt(); // We're in trouble!
fail("Thread did not terminate after " + ms + " ms: " + t);
// getLogWriter().warning("Thread did not terminate"
// /* , new Exception()*/
// );
}
long elapsedMs = (System.currentTimeMillis() - start);
if (elapsedMs > 0) {
String msg = "Thread " + t + " took "
+ elapsedMs
+ " ms to exit.";
logger.info(msg);
}
}
public static void dumpStackTrace(Thread t, StackTraceElement[] stack, LogWriter logger) {
StringBuilder msg = new StringBuilder();
msg.append("Thread=<")
.append(t)
.append("> stackDump:\n");
for (int i=0; i < stack.length; i++) {
msg.append("\t")
.append(stack[i])
.append("\n");
}
logger.info(msg.toString());
}
/**
* Dump all thread stacks
*/
public static void dumpMyThreads(LogWriter logger) {
OSProcess.printStacks(0, false);
}
/**
* A class that represents an currently logged expected exception, which
* should be removed
*
* @author Mitch Thomas
* @since 5.7bugfix
*/
public static class ExpectedException implements Serializable {
private static final long serialVersionUID = 1L;
final String ex;
final transient VM v;
public ExpectedException(String exception) {
this.ex = exception;
this.v = null;
}
ExpectedException(String exception, VM vm) {
this.ex = exception;
this.v = vm;
}
public String getRemoveString() {
return "<ExpectedException action=remove>" + ex + "</ExpectedException>";
}
public String getAddString() {
return "<ExpectedException action=add>" + ex + "</ExpectedException>";
}
public void remove() {
SerializableRunnable removeRunnable = new SerializableRunnable(
"removeExpectedExceptions") {
public void run() {
final String remove = getRemoveString();
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) {
sys.getLogWriter().info(remove);
}
try {
getLogWriter().info(remove);
} catch (Exception noHydraLogger) {
}
logger.info(remove);
}
};
if (this.v != null) {
v.invoke(removeRunnable);
}
else {
invokeInEveryVM(removeRunnable);
}
String s = getRemoveString();
LogManager.getLogger(LogService.BASE_LOGGER_NAME).info(s);
// log it locally
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) { // avoid creating a system
sys.getLogWriter().info(s);
}
getLogWriter().info(s);
}
}
/**
* Log in all VMs, in both the test logger and the GemFire logger the
* expected exception string to prevent grep logs from complaining. The
* expected string is used by the GrepLogs utility and so can contain
* regular expression characters.
*
* If you do not remove the expected exception, it will be removed at the
* end of your test case automatically.
*
* @since 5.7bugfix
* @param exception
* the exception string to expect
* @return an ExpectedException instance for removal
*/
public static ExpectedException addExpectedException(final String exception) {
return addExpectedException(exception, null);
}
/**
* Log in all VMs, in both the test logger and the GemFire logger the
* expected exception string to prevent grep logs from complaining. The
* expected string is used by the GrepLogs utility and so can contain
* regular expression characters.
*
* @since 5.7bugfix
* @param exception
* the exception string to expect
* @param v
* the VM on which to log the expected exception or null for all VMs
* @return an ExpectedException instance for removal purposes
*/
public static ExpectedException addExpectedException(final String exception,
VM v) {
final ExpectedException ret;
if (v != null) {
ret = new ExpectedException(exception, v);
}
else {
ret = new ExpectedException(exception);
}
// define the add and remove expected exceptions
final String add = ret.getAddString();
SerializableRunnable addRunnable = new SerializableRunnable(
"addExpectedExceptions") {
public void run() {
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) {
sys.getLogWriter().info(add);
}
try {
getLogWriter().info(add);
} catch (Exception noHydraLogger) {
}
logger.info(add);
}
};
if (v != null) {
v.invoke(addRunnable);
}
else {
invokeInEveryVM(addRunnable);
}
LogManager.getLogger(LogService.BASE_LOGGER_NAME).info(add);
// Log it locally too
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) { // avoid creating a cache
sys.getLogWriter().info(add);
}
getLogWriter().info(add);
expectedExceptions.add(ret);
return ret;
}
/**
* delete locator state files. Use this after getting a random port
* to ensure that an old locator state file isn't picked up by the
* new locator you're starting.
* @param ports
*/
public void deleteLocatorStateFile(int... ports) {
for (int i=0; i<ports.length; i++) {
File stateFile = new File("locator"+ports[i]+"view.dat");
if (stateFile.exists()) {
stateFile.delete();
}
}
}
}
|
gemfire-core/src/test/java/dunit/DistributedTestCase.java
|
/*
* 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 dunit;
import java.io.File;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.experimental.categories.Category;
import org.springframework.data.gemfire.support.GemfireCache;
import junit.framework.TestCase;
import com.gemstone.gemfire.InternalGemFireError;
import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.SystemFailure;
import com.gemstone.gemfire.admin.internal.AdminDistributedSystemImpl;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.DiskStoreFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.hdfs.internal.HDFSStoreImpl;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HoplogConfig;
import com.gemstone.gemfire.cache.query.QueryTestUtils;
import com.gemstone.gemfire.cache.query.internal.QueryObserverHolder;
import com.gemstone.gemfire.cache30.ClientServerTestCase;
import com.gemstone.gemfire.cache30.GlobalLockingDUnitTest;
import com.gemstone.gemfire.cache30.MultiVMRegionTestCase;
import com.gemstone.gemfire.cache30.RegionTestCase;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.distributed.Locator;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.DistributionConfigImpl;
import com.gemstone.gemfire.distributed.internal.DistributionMessageObserver;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem.CreationStackGenerator;
import com.gemstone.gemfire.distributed.internal.membership.gms.MembershipManagerHelper;
import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.internal.InternalDataSerializer;
import com.gemstone.gemfire.internal.InternalInstantiator;
import com.gemstone.gemfire.internal.OSProcess;
import com.gemstone.gemfire.internal.SocketCreator;
import com.gemstone.gemfire.internal.admin.ClientStatsManager;
import com.gemstone.gemfire.internal.cache.DiskStoreObserver;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.HARegion;
import com.gemstone.gemfire.internal.cache.InitialImageOperation;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.tier.InternalClientMembership;
import com.gemstone.gemfire.internal.cache.tier.sockets.CacheServerTestUtil;
import com.gemstone.gemfire.internal.cache.tier.sockets.ClientProxyMembershipID;
import com.gemstone.gemfire.internal.cache.tier.sockets.DataSerializerPropogationDUnitTest;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheCreation;
import com.gemstone.gemfire.internal.logging.InternalLogWriter;
import com.gemstone.gemfire.internal.logging.LocalLogWriter;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.internal.logging.LogWriterFactory;
import com.gemstone.gemfire.internal.logging.LogWriterImpl;
import com.gemstone.gemfire.internal.logging.ManagerLogWriter;
import com.gemstone.gemfire.internal.logging.log4j.LogWriterLogger;
import com.gemstone.gemfire.management.internal.cli.LogWrapper;
import com.gemstone.gemfire.test.junit.categories.DistributedTest;
import dunit.standalone.DUnitLauncher;
/**
* This class is the superclass of all distributed unit tests.
*
* tests/hydra/JUnitTestTask is the main DUnit driver. It supports two
* additional public static methods if they are defined in the test case:
*
* public static void caseSetUp() -- comparable to JUnit's BeforeClass annotation
*
* public static void caseTearDown() -- comparable to JUnit's AfterClass annotation
*
* @author David Whitlock
*/
@Category(DistributedTest.class)
@SuppressWarnings("serial")
public abstract class DistributedTestCase extends TestCase implements java.io.Serializable {
private static final Logger logger = LogService.getLogger();
private static final LogWriterLogger oldLogger = LogWriterLogger.create(logger);
private static final LinkedHashSet<String> testHistory = new LinkedHashSet<String>();
private static void setUpCreationStackGenerator() {
// the following is moved from InternalDistributedSystem to fix #51058
InternalDistributedSystem.TEST_CREATION_STACK_GENERATOR.set(
new CreationStackGenerator() {
@Override
public Throwable generateCreationStack(final DistributionConfig config) {
final StringBuilder sb = new StringBuilder();
final String[] validAttributeNames = config.getAttributeNames();
for (int i = 0; i < validAttributeNames.length; i++) {
final String attName = validAttributeNames[i];
final Object actualAtt = config.getAttributeObject(attName);
String actualAttStr = actualAtt.toString();
sb.append(" ");
sb.append(attName);
sb.append("=\"");
if (actualAtt.getClass().isArray()) {
actualAttStr = InternalDistributedSystem.arrayToString(actualAtt);
}
sb.append(actualAttStr);
sb.append("\"");
sb.append("\n");
}
return new Throwable("Creating distributed system with the following configuration:\n" + sb.toString());
}
});
}
private static void tearDownCreationStackGenerator() {
InternalDistributedSystem.TEST_CREATION_STACK_GENERATOR.set(InternalDistributedSystem.DEFAULT_CREATION_STACK_GENERATOR);
}
/** This VM's connection to the distributed system */
public static InternalDistributedSystem system;
private static Class lastSystemCreatedInTest;
private static Properties lastSystemProperties;
public static volatile String testName;
private static ConcurrentLinkedQueue<ExpectedException> expectedExceptions = new ConcurrentLinkedQueue<ExpectedException>();
/** For formatting timing info */
private static final DecimalFormat format = new DecimalFormat("###.###");
public static boolean reconnect = false;
public static final boolean logPerTest = Boolean.getBoolean("dunitLogPerTest");
/////////////////////// Utility Methods ///////////////////////
public void attachDebugger(VM vm, final String msg) {
vm.invoke(new SerializableRunnable("Attach Debugger") {
public void run() {
com.gemstone.gemfire.internal.util.DebuggerSupport.
waitForJavaDebugger(getSystem().getLogWriter().convertToLogWriterI18n(), msg);
}
});
}
/**
* Invokes a <code>SerializableRunnable</code> in every VM that
* DUnit knows about.
*
* @see VM#invoke(Runnable)
*/
public static void invokeInEveryVM(SerializableRunnable work) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invoke(work);
}
}
}
public static void invokeInLocator(SerializableRunnable work) {
Host.getLocator().invoke(work);
}
/**
* Invokes a <code>SerializableCallable</code> in every VM that
* DUnit knows about.
*
* @return a Map of results, where the key is the VM and the value is the result
* @see VM#invoke(Callable)
*/
protected static Map invokeInEveryVM(SerializableCallable work) {
HashMap ret = new HashMap();
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
ret.put(vm, vm.invoke(work));
}
}
return ret;
}
/**
* Invokes a method in every remote VM that DUnit knows about.
*
* @see VM#invoke(Class, String)
*/
protected static void invokeInEveryVM(Class c, String method) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invoke(c, method);
}
}
}
/**
* Invokes a method in every remote VM that DUnit knows about.
*
* @see VM#invoke(Class, String)
*/
protected static void invokeInEveryVM(Class c, String method, Object[] methodArgs) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invoke(c, method, methodArgs);
}
}
}
/**
* The number of milliseconds to try repeating validation code in the
* event that AssertionFailedError is thrown. For ACK scopes, no
* repeat should be necessary.
*/
protected long getRepeatTimeoutMs() {
return 0;
}
protected void invokeRepeatingIfNecessary(VM vm, RepeatableRunnable task) {
vm.invokeRepeatingIfNecessary(task, getRepeatTimeoutMs());
}
/**
* Invokes a <code>SerializableRunnable</code> in every VM that
* DUnit knows about. If work.run() throws an assertion failure,
* its execution is repeated, until no assertion failure occurs or
* repeatTimeout milliseconds have passed.
*
* @see VM#invoke(Runnable)
*/
protected void invokeInEveryVMRepeatingIfNecessary(RepeatableRunnable work) {
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
vm.invokeRepeatingIfNecessary(work, getRepeatTimeoutMs());
}
}
}
/** Return the total number of VMs on all hosts */
protected static int getVMCount() {
int count = 0;
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
count += host.getVMCount();
}
return count;
}
/** print a stack dump for this vm
@author bruce
@since 5.0
*/
public static void dumpStack() {
com.gemstone.gemfire.internal.OSProcess.printStacks(0, false);
}
/** print a stack dump for the given vm
@author bruce
@since 5.0
*/
public static void dumpStack(VM vm) {
vm.invoke(dunit.DistributedTestCase.class, "dumpStack");
}
/** print stack dumps for all vms on the given host
@author bruce
@since 5.0
*/
public static void dumpStack(Host host) {
for (int v=0; v < host.getVMCount(); v++) {
host.getVM(v).invoke(dunit.DistributedTestCase.class, "dumpStack");
}
}
/** print stack dumps for all vms
@author bruce
@since 5.0
*/
public static void dumpAllStacks() {
for (int h=0; h < Host.getHostCount(); h++) {
dumpStack(Host.getHost(h));
}
}
public static String noteTiming(long operations, String operationUnit,
long beginTime, long endTime,
String timeUnit)
{
long delta = endTime - beginTime;
StringBuffer sb = new StringBuffer();
sb.append(" Performed ");
sb.append(operations);
sb.append(" ");
sb.append(operationUnit);
sb.append(" in ");
sb.append(delta);
sb.append(" ");
sb.append(timeUnit);
sb.append("\n");
double ratio = ((double) operations) / ((double) delta);
sb.append(" ");
sb.append(format.format(ratio));
sb.append(" ");
sb.append(operationUnit);
sb.append(" per ");
sb.append(timeUnit);
sb.append("\n");
ratio = ((double) delta) / ((double) operations);
sb.append(" ");
sb.append(format.format(ratio));
sb.append(" ");
sb.append(timeUnit);
sb.append(" per ");
sb.append(operationUnit);
sb.append("\n");
return sb.toString();
}
/**
* Creates a new LogWriter and adds it to the config properties. The config
* can then be used to connect to DistributedSystem, thus providing early
* access to the LogWriter before connecting. This call does not connect
* to the DistributedSystem. It simply creates and returns the LogWriter
* that will eventually be used by the DistributedSystem that connects using
* config.
*
* @param config the DistributedSystem config properties to add LogWriter to
* @return early access to the DistributedSystem LogWriter
*/
protected static LogWriter createLogWriter(Properties config) { // TODO:LOG:CONVERT: this is being used for ExpectedExceptions
Properties nonDefault = config;
if (nonDefault == null) {
nonDefault = new Properties();
}
addHydraProperties(nonDefault);
DistributionConfig dc = new DistributionConfigImpl(nonDefault);
LogWriter logger = LogWriterFactory.createLogWriterLogger(
false/*isLoner*/, false/*isSecurityLog*/, dc,
false);
// if config was non-null, then these will be added to it...
nonDefault.put(DistributionConfig.LOG_WRITER_NAME, logger);
return logger;
}
/**
* Fetches the GemFireDescription for this test and adds its
* DistributedSystem properties to the provided props parameter.
*
* @param config the properties to add hydra's test properties to
*/
protected static void addHydraProperties(Properties config) {
Properties p = DUnitEnv.get().getDistributedSystemProperties();
for (Iterator iter = p.entrySet().iterator();
iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (config.getProperty(key) == null) {
config.setProperty(key, value);
}
}
}
//////////////////////// Constructors ////////////////////////
/**
* Creates a new <code>DistributedTestCase</code> test with the
* given name.
*/
public DistributedTestCase(String name) {
super(name);
DUnitLauncher.launchIfNeeded();
}
/////////////////////// Instance Methods ///////////////////////
protected Class getTestClass() {
Class clazz = getClass();
while (clazz.getDeclaringClass() != null) {
clazz = clazz.getDeclaringClass();
}
return clazz;
}
/**
* This finds the log level configured for the test run. It should be used
* when creating a new distributed system if you want to specify a log level.
* @return the dunit log-level setting
*/
public static String getDUnitLogLevel() {
Properties p = DUnitEnv.get().getDistributedSystemProperties();
String result = p.getProperty(DistributionConfig.LOG_LEVEL_NAME);
if (result == null) {
result = ManagerLogWriter.levelToString(DistributionConfig.DEFAULT_LOG_LEVEL);
}
return result;
}
public final static Properties getAllDistributedSystemProperties(Properties props) {
Properties p = DUnitEnv.get().getDistributedSystemProperties();
// our tests do not expect auto-reconnect to be on by default
if (!p.contains(DistributionConfig.DISABLE_AUTO_RECONNECT_NAME)) {
p.put(DistributionConfig.DISABLE_AUTO_RECONNECT_NAME, "true");
}
for (Iterator iter = props.entrySet().iterator();
iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
Object value = entry.getValue();
p.put(key, value);
}
return p;
}
public void setSystem(Properties props, DistributedSystem ds) {
system = (InternalDistributedSystem)ds;
lastSystemProperties = props;
lastSystemCreatedInTest = getTestClass();
}
/**
* Returns this VM's connection to the distributed system. If
* necessary, the connection will be lazily created using the given
* <code>Properties</code>. Note that this method uses hydra's
* configuration to determine the location of log files, etc.
* Note: "final" was removed so that WANTestBase can override this method.
* This was part of the xd offheap merge.
*
* @see hydra.DistributedConnectionMgr#connect
* @since 3.0
*/
public /*final*/ InternalDistributedSystem getSystem(Properties props) {
// Setting the default disk store name is now done in setUp
if (system == null) {
system = InternalDistributedSystem.getAnyInstance();
}
if (system == null || !system.isConnected()) {
// Figure out our distributed system properties
Properties p = getAllDistributedSystemProperties(props);
lastSystemCreatedInTest = getTestClass();
if (logPerTest) {
String testMethod = getTestName();
String testName = lastSystemCreatedInTest.getName() + '-' + testMethod;
String oldLogFile = p.getProperty(DistributionConfig.LOG_FILE_NAME);
p.put(DistributionConfig.LOG_FILE_NAME,
oldLogFile.replace("system.log", testName+".log"));
String oldStatFile = p.getProperty(DistributionConfig.STATISTIC_ARCHIVE_FILE_NAME);
p.put(DistributionConfig.STATISTIC_ARCHIVE_FILE_NAME,
oldStatFile.replace("statArchive.gfs", testName+".gfs"));
}
system = (InternalDistributedSystem)DistributedSystem.connect(p);
lastSystemProperties = p;
} else {
boolean needNewSystem = false;
if(!getTestClass().equals(lastSystemCreatedInTest)) {
Properties newProps = getAllDistributedSystemProperties(props);
needNewSystem = !newProps.equals(lastSystemProperties);
if(needNewSystem) {
getLogWriter().info(
"Test class has changed and the new DS properties are not an exact match. "
+ "Forcing DS disconnect. Old props = "
+ lastSystemProperties + "new props=" + newProps);
}
} else {
Properties activeProps = system.getProperties();
for (Iterator iter = props.entrySet().iterator();
iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (!value.equals(activeProps.getProperty(key))) {
needNewSystem = true;
getLogWriter().info("Forcing DS disconnect. For property " + key
+ " old value = " + activeProps.getProperty(key)
+ " new value = " + value);
break;
}
}
}
if(needNewSystem) {
// the current system does not meet our needs to disconnect and
// call recursively to get a new system.
getLogWriter().info("Disconnecting from current DS in order to make a new one");
disconnectFromDS();
getSystem(props);
}
}
return system;
}
/**
* Crash the cache in the given VM in such a way that it immediately stops communicating with
* peers. This forces the VM's membership manager to throw a ForcedDisconnectException by
* forcibly terminating the JGroups protocol stack with a fake EXIT event.<p>
*
* NOTE: if you use this method be sure that you clean up the VM before the end of your
* test with disconnectFromDS() or disconnectAllFromDS().
*/
public boolean crashDistributedSystem(VM vm) {
return (Boolean)vm.invoke(new SerializableCallable("crash distributed system") {
public Object call() throws Exception {
DistributedSystem msys = InternalDistributedSystem.getAnyInstance();
crashDistributedSystem(msys);
return true;
}
});
}
/**
* Crash the cache in the given VM in such a way that it immediately stops communicating with
* peers. This forces the VM's membership manager to throw a ForcedDisconnectException by
* forcibly terminating the JGroups protocol stack with a fake EXIT event.<p>
*
* NOTE: if you use this method be sure that you clean up the VM before the end of your
* test with disconnectFromDS() or disconnectAllFromDS().
*/
public void crashDistributedSystem(final DistributedSystem msys) {
MembershipManagerHelper.crashDistributedSystem(msys);
MembershipManagerHelper.inhibitForcedDisconnectLogging(false);
WaitCriterion wc = new WaitCriterion() {
public boolean done() {
return !msys.isConnected();
}
public String description() {
return "waiting for distributed system to finish disconnecting: " + msys;
}
};
// try {
waitForCriterion(wc, 10000, 1000, true);
// } finally {
// dumpMyThreads(getLogWriter());
// }
}
private String getDefaultDiskStoreName() {
String vmid = System.getProperty("vmid");
return "DiskStore-" + vmid + "-"+ getTestClass().getCanonicalName() + "." + getTestName();
}
/**
* Returns this VM's connection to the distributed system. If
* necessary, the connection will be lazily created using the
* <code>Properties</code> returned by {@link
* #getDistributedSystemProperties}.
*
* @see #getSystem(Properties)
*
* @since 3.0
*/
public final InternalDistributedSystem getSystem() {
return getSystem(this.getDistributedSystemProperties());
}
/**
* Returns a loner distributed system that isn't connected to other
* vms
*
* @since 6.5
*/
public final InternalDistributedSystem getLonerSystem() {
Properties props = this.getDistributedSystemProperties();
props.put(DistributionConfig.MCAST_PORT_NAME, "0");
props.put(DistributionConfig.LOCATORS_NAME, "");
return getSystem(props);
}
/**
* Returns a loner distributed system in combination with enforceUniqueHost
* and redundancyZone properties.
* Added specifically to test scenario of defect #47181.
*/
public final InternalDistributedSystem getLonerSystemWithEnforceUniqueHost() {
Properties props = this.getDistributedSystemProperties();
props.put(DistributionConfig.MCAST_PORT_NAME, "0");
props.put(DistributionConfig.LOCATORS_NAME, "");
props.put(DistributionConfig.ENFORCE_UNIQUE_HOST_NAME, "true");
props.put(DistributionConfig.REDUNDANCY_ZONE_NAME, "zone1");
return getSystem(props);
}
/**
* Returns whether or this VM is connected to a {@link
* DistributedSystem}.
*/
public final boolean isConnectedToDS() {
return system != null && system.isConnected();
}
/**
* Returns a <code>Properties</code> object used to configure a
* connection to a {@link
* com.gemstone.gemfire.distributed.DistributedSystem}.
* Unless overridden, this method will return an empty
* <code>Properties</code> object.
*
* @since 3.0
*/
public Properties getDistributedSystemProperties() {
return new Properties();
}
/**
* Sets up the test (noop).
*/
@Override
public void setUp() throws Exception {
logTestHistory();
setUpCreationStackGenerator();
testName = getName();
System.setProperty(HoplogConfig.ALLOW_LOCAL_HDFS_PROP, "true");
if (testName != null) {
GemFireCacheImpl.setDefaultDiskStoreName(getDefaultDiskStoreName());
String baseDefaultDiskStoreName = getTestClass().getCanonicalName() + "." + getTestName();
for (int h = 0; h < Host.getHostCount(); h++) {
Host host = Host.getHost(h);
for (int v = 0; v < host.getVMCount(); v++) {
VM vm = host.getVM(v);
String vmDefaultDiskStoreName = "DiskStore-" + h + "-" + v + "-" + baseDefaultDiskStoreName;
vm.invoke(DistributedTestCase.class, "perVMSetUp", new Object[] {testName, vmDefaultDiskStoreName});
}
}
}
System.out.println("\n\n[setup] START TEST " + getClass().getSimpleName()+"."+testName+"\n\n");
}
/**
* Write a message to the log about what tests have ran previously. This
* makes it easier to figure out if a previous test may have caused problems
*/
private void logTestHistory() {
String classname = getClass().getSimpleName();
testHistory.add(classname);
System.out.println("Previously run tests: " + testHistory);
}
public static void perVMSetUp(String name, String defaultDiskStoreName) {
setTestName(name);
GemFireCacheImpl.setDefaultDiskStoreName(defaultDiskStoreName);
System.setProperty(HoplogConfig.ALLOW_LOCAL_HDFS_PROP, "true");
}
public static void setTestName(String name) {
testName = name;
}
public static String getTestName() {
return testName;
}
/**
* For logPerTest to work, we have to disconnect from the DS, but all
* subclasses do not call super.tearDown(). To prevent this scenario
* this method has been declared final. Subclasses must now override
* {@link #tearDown2()} instead.
* @throws Exception
*/
@Override
public final void tearDown() throws Exception {
tearDownCreationStackGenerator();
tearDown2();
realTearDown();
tearDownAfter();
}
/**
* Tears down the test. This method is called by the final {@link #tearDown()} method and should be overridden to
* perform actual test cleanup and release resources used by the test. The tasks executed by this method are
* performed before the DUnit test framework using Hydra cleans up the client VMs.
* <p/>
* @throws Exception if the tear down process and test cleanup fails.
* @see #tearDown
* @see #tearDownAfter()
*/
// TODO rename this method to tearDownBefore and change the access modifier to protected!
public void tearDown2() throws Exception {
}
protected void realTearDown() throws Exception {
if (logPerTest) {
disconnectFromDS();
invokeInEveryVM(DistributedTestCase.class, "disconnectFromDS");
}
cleanupAllVms();
}
/**
* Tears down the test. Performs additional tear down tasks after the DUnit tests framework using Hydra cleans up
* the client VMs. This method is called by the final {@link #tearDown()} method and should be overridden to perform
* post tear down activities.
* <p/>
* @throws Exception if the test tear down process fails.
* @see #tearDown()
* @see #tearDown2()
*/
protected void tearDownAfter() throws Exception {
}
public static void cleanupAllVms()
{
cleanupThisVM();
invokeInEveryVM(DistributedTestCase.class, "cleanupThisVM");
invokeInLocator(new SerializableRunnable() {
public void run() {
DistributionMessageObserver.setInstance(null);
unregisterInstantiatorsInThisVM();
}
});
DUnitLauncher.closeAndCheckForSuspects();
}
private static void cleanupThisVM() {
closeCache();
SocketCreator.resolve_dns = true;
CacheCreation.clearThreadLocals();
System.getProperties().remove("gemfire.log-level");
System.getProperties().remove("jgroups.resolve_dns");
InitialImageOperation.slowImageProcessing = 0;
DistributionMessageObserver.setInstance(null);
QueryTestUtils.setCache(null);
CacheServerTestUtil.clearCacheReference();
RegionTestCase.preSnapshotRegion = null;
GlobalLockingDUnitTest.region_testBug32356 = null;
LogWrapper.close();
ClientProxyMembershipID.system = null;
MultiVMRegionTestCase.CCRegion = null;
InternalClientMembership.unregisterAllListeners();
ClientStatsManager.cleanupForTests();
ClientServerTestCase.AUTO_LOAD_BALANCE = false;
unregisterInstantiatorsInThisVM();
DistributionMessageObserver.setInstance(null);
QueryObserverHolder.reset();
DiskStoreObserver.setInstance(null);
System.getProperties().remove("gemfire.log-level");
System.getProperties().remove("jgroups.resolve_dns");
if (InternalDistributedSystem.systemAttemptingReconnect != null) {
InternalDistributedSystem.systemAttemptingReconnect.stopReconnecting();
}
ExpectedException ex;
while((ex = expectedExceptions.poll()) != null) {
ex.remove();
}
}
private static void closeCache() {
GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
if(cache != null && !cache.isClosed()) {
destroyRegions(cache);
cache.close();
}
}
protected static final void destroyRegions(Cache cache)
throws InternalGemFireError, Error, VirtualMachineError {
if (cache != null && !cache.isClosed()) {
//try to destroy the root regions first so that
//we clean up any persistent files.
for (Iterator itr = cache.rootRegions().iterator(); itr.hasNext();) {
Region root = (Region)itr.next();
//for colocated regions you can't locally destroy a partitioned
//region.
if(root.isDestroyed() || root instanceof HARegion || root instanceof PartitionedRegion) {
continue;
}
try {
root.localDestroyRegion("teardown");
}
catch (VirtualMachineError e) {
SystemFailure.initiateFailure(e);
throw e;
}
catch (Throwable t) {
getLogWriter().error(t);
}
}
}
}
public static void unregisterAllDataSerializersFromAllVms()
{
unregisterDataSerializerInThisVM();
invokeInEveryVM(new SerializableRunnable() {
public void run() {
unregisterDataSerializerInThisVM();
}
});
invokeInLocator(new SerializableRunnable() {
public void run() {
unregisterDataSerializerInThisVM();
}
});
}
public static void unregisterInstantiatorsInThisVM() {
// unregister all the instantiators
InternalInstantiator.reinitialize();
assertEquals(0, InternalInstantiator.getInstantiators().length);
}
public static void unregisterDataSerializerInThisVM()
{
DataSerializerPropogationDUnitTest.successfullyLoadedTestDataSerializer = false;
// unregister all the Dataserializers
InternalDataSerializer.reinitialize();
// ensure that all are unregistered
assertEquals(0, InternalDataSerializer.getSerializers().length);
}
protected static void disconnectAllFromDS() {
disconnectFromDS();
invokeInEveryVM(DistributedTestCase.class,
"disconnectFromDS");
}
/**
* Disconnects this VM from the distributed system
*/
public static void disconnectFromDS() {
testName = null;
GemFireCacheImpl.testCacheXml = null;
if (system != null) {
system.disconnect();
system = null;
}
for (;;) {
DistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
if (ds == null) {
break;
}
try {
ds.disconnect();
}
catch (Exception e) {
// ignore
}
}
{
AdminDistributedSystemImpl ads =
AdminDistributedSystemImpl.getConnectedInstance();
if (ads != null) {// && ads.isConnected()) {
ads.disconnect();
}
}
}
/**
* Strip the package off and gives just the class name.
* Needed because of Windows file name limits.
*/
private String getShortClassName() {
String result = this.getClass().getName();
int idx = result.lastIndexOf('.');
if (idx != -1) {
result = result.substring(idx+1);
}
return result;
}
/** get the host name to use for a server cache in client/server dunit
* testing
* @param host
* @return the host name
*/
public static String getServerHostName(Host host) {
return System.getProperty("gemfire.server-bind-address") != null?
System.getProperty("gemfire.server-bind-address")
: host.getHostName();
}
/** get the IP literal name for the current host, use this instead of
* "localhost" to avoid IPv6 name resolution bugs in the JDK/machine config.
* @return an ip literal, this method honors java.net.preferIPvAddresses
*/
public static String getIPLiteral() {
try {
return SocketCreator.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new Error("problem determining host IP address", e);
}
}
/**
* Get the port that the standard dunit locator is listening on.
* @return
*/
public static int getDUnitLocatorPort() {
return DUnitEnv.get().getLocatorPort();
}
/**
* Returns a unique name for this test method. It is based on the
* name of the class as well as the name of the method.
*/
public String getUniqueName() {
return getShortClassName() + "_" + this.getName();
}
/**
* Returns a <code>LogWriter</code> for logging information
* @deprecated Use a static logger from the log4j2 LogService.getLogger instead.
*/
@Deprecated
public static InternalLogWriter getLogWriter() {
return oldLogger;
}
/**
* Helper method that causes this test to fail because of the given
* exception.
*/
public static void fail(String message, Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
pw.print(message);
pw.print(": ");
ex.printStackTrace(pw);
fail(sw.toString());
}
// utility methods
/** pause for a default interval */
protected void pause() {
pause(250);
}
/**
* Use of this function indicates a place in the tests tree where t
* he use of Thread.sleep() is
* highly questionable.
* <p>
* Some places in the system, especially those that test expirations and other
* timeouts, have a very good reason to call {@link Thread#sleep(long)}. The
* <em>other</em> places are marked by the use of this method.
*
* @param ms
*/
static public final void staticPause(int ms) {
// getLogWriter().info("FIXME: Pausing for " + ms + " ms..."/*, new Exception()*/);
final long target = System.currentTimeMillis() + ms;
try {
for (;;) {
long msLeft = target - System.currentTimeMillis();
if (msLeft <= 0) {
break;
}
Thread.sleep(msLeft);
}
}
catch (InterruptedException e) {
fail("interrupted", e);
}
}
/**
* Blocks until the clock used for expiration moves forward.
* @return the last time stamp observed
*/
public static final long waitForExpiryClockToChange(LocalRegion lr) {
return waitForExpiryClockToChange(lr, lr.cacheTimeMillis());
}
/**
* Blocks until the clock used for expiration moves forward.
* @param baseTime the timestamp that the clock must exceed
* @return the last time stamp observed
*/
public static final long waitForExpiryClockToChange(LocalRegion lr, final long baseTime) {
long nowTime;
do {
Thread.yield();
nowTime = lr.cacheTimeMillis();
} while ((nowTime - baseTime) <= 0L);
return nowTime;
}
/** pause for specified ms interval
* Make sure system clock has advanced by the specified number of millis before
* returning.
*/
public static final void pause(int ms) {
LogWriter log = getLogWriter();
if (ms >= 1000 || log.fineEnabled()) { // check for fine but log at info
getLogWriter().info("Pausing for " + ms + " ms..."/*, new Exception()*/);
}
final long target = System.currentTimeMillis() + ms;
try {
for (;;) {
long msLeft = target - System.currentTimeMillis();
if (msLeft <= 0) {
break;
}
Thread.sleep(msLeft);
}
}
catch (InterruptedException e) {
fail("interrupted", e);
}
}
public interface WaitCriterion {
public boolean done();
public String description();
}
public interface WaitCriterion2 extends WaitCriterion {
/**
* If this method returns true then quit waiting even if we are not done.
* This allows a wait to fail early.
*/
public boolean stopWaiting();
}
/**
* If true, we randomize the amount of time we wait before polling a
* {@link WaitCriterion}.
*/
static private final boolean USE_JITTER = true;
static private final Random jitter = new Random();
/**
* Return a jittered interval up to a maximum of <code>ms</code>
* milliseconds, inclusive.
*
* The result is bounded by 50 ms as a minimum and 5000 ms as a maximum.
*
* @param ms total amount of time to wait
* @return randomized interval we should wait
*/
private static int jitterInterval(long ms) {
final int minLegal = 50;
final int maxLegal = 5000;
if (ms <= minLegal) {
return (int)ms; // Don't ever jitter anything below this.
}
int maxReturn = maxLegal;
if (ms < maxLegal) {
maxReturn = (int)ms;
}
return minLegal + jitter.nextInt(maxReturn - minLegal + 1);
}
/**
* Wait until given criterion is met
* @param ev criterion to wait on
* @param ms total time to wait, in milliseconds
* @param interval pause interval between waits
* @param throwOnTimeout if false, don't generate an error
*/
static public void waitForCriterion(WaitCriterion ev, long ms,
long interval, boolean throwOnTimeout) {
long waitThisTime;
if (USE_JITTER) {
waitThisTime = jitterInterval(interval);
}
else {
waitThisTime = interval;
}
final long tilt = System.currentTimeMillis() + ms;
for (;;) {
// getLogWriter().info("Testing to see if event has occurred: " + ev.description());
if (ev.done()) {
return; // success
}
if (ev instanceof WaitCriterion2) {
WaitCriterion2 ev2 = (WaitCriterion2)ev;
if (ev2.stopWaiting()) {
if (throwOnTimeout) {
fail("stopWaiting returned true: " + ev.description());
}
return;
}
}
// Calculate time left
long timeLeft = tilt - System.currentTimeMillis();
if (timeLeft <= 0) {
if (!throwOnTimeout) {
return; // not an error, but we're done
}
fail("Event never occurred after " + ms + " ms: " + ev.description());
}
if (waitThisTime > timeLeft) {
waitThisTime = timeLeft;
}
// Wait a little bit
Thread.yield();
try {
// getLogWriter().info("waiting " + waitThisTime + "ms for " + ev.description());
Thread.sleep(waitThisTime);
} catch (InterruptedException e) {
fail("interrupted");
}
}
}
/**
* Wait on a mutex. This is done in a loop in order to address the
* "spurious wakeup" "feature" in Java.
* @param ev condition to test
* @param mutex object to lock and wait on
* @param ms total amount of time to wait
* @param interval interval to pause for the wait
* @param throwOnTimeout if false, no error is thrown.
*/
static public void waitMutex(WaitCriterion ev, Object mutex, long ms,
long interval, boolean throwOnTimeout) {
final long tilt = System.currentTimeMillis() + ms;
long waitThisTime;
if (USE_JITTER) {
waitThisTime = jitterInterval(interval);
}
else {
waitThisTime = interval;
}
synchronized (mutex) {
for (;;) {
if (ev.done()) {
break;
}
long timeLeft = tilt - System.currentTimeMillis();
if (timeLeft <= 0) {
if (!throwOnTimeout) {
return; // not an error, but we're done
}
fail("Event never occurred after " + ms + " ms: " + ev.description());
}
if (waitThisTime > timeLeft) {
waitThisTime = timeLeft;
}
try {
mutex.wait(waitThisTime);
} catch (InterruptedException e) {
fail("interrupted");
}
} // for
} // synchronized
}
/**
* Wait for a thread to join
* @param t thread to wait on
* @param ms maximum time to wait
* @throws AssertionFailure if the thread does not terminate
*/
static public void join(Thread t, long ms, LogWriter logger) {
final long tilt = System.currentTimeMillis() + ms;
final long incrementalWait;
if (USE_JITTER) {
incrementalWait = jitterInterval(ms);
}
else {
incrementalWait = ms; // wait entire time, no looping.
}
final long start = System.currentTimeMillis();
for (;;) {
// I really do *not* understand why this check is necessary
// but it is, at least with JDK 1.6. According to the source code
// and the javadocs, one would think that join() would exit immediately
// if the thread is dead. However, I can tell you from experimentation
// that this is not the case. :-( djp 2008-12-08
if (!t.isAlive()) {
break;
}
try {
t.join(incrementalWait);
} catch (InterruptedException e) {
fail("interrupted");
}
if (System.currentTimeMillis() >= tilt) {
break;
}
} // for
if (logger == null) {
logger = new LocalLogWriter(LogWriterImpl.INFO_LEVEL, System.out);
}
if (t.isAlive()) {
logger.info("HUNG THREAD");
dumpStackTrace(t, t.getStackTrace(), logger);
dumpMyThreads(logger);
t.interrupt(); // We're in trouble!
fail("Thread did not terminate after " + ms + " ms: " + t);
// getLogWriter().warning("Thread did not terminate"
// /* , new Exception()*/
// );
}
long elapsedMs = (System.currentTimeMillis() - start);
if (elapsedMs > 0) {
String msg = "Thread " + t + " took "
+ elapsedMs
+ " ms to exit.";
logger.info(msg);
}
}
public static void dumpStackTrace(Thread t, StackTraceElement[] stack, LogWriter logger) {
StringBuilder msg = new StringBuilder();
msg.append("Thread=<")
.append(t)
.append("> stackDump:\n");
for (int i=0; i < stack.length; i++) {
msg.append("\t")
.append(stack[i])
.append("\n");
}
logger.info(msg.toString());
}
/**
* Dump all thread stacks
*/
public static void dumpMyThreads(LogWriter logger) {
OSProcess.printStacks(0, false);
}
/**
* A class that represents an currently logged expected exception, which
* should be removed
*
* @author Mitch Thomas
* @since 5.7bugfix
*/
public static class ExpectedException implements Serializable {
private static final long serialVersionUID = 1L;
final String ex;
final transient VM v;
public ExpectedException(String exception) {
this.ex = exception;
this.v = null;
}
ExpectedException(String exception, VM vm) {
this.ex = exception;
this.v = vm;
}
public String getRemoveString() {
return "<ExpectedException action=remove>" + ex + "</ExpectedException>";
}
public String getAddString() {
return "<ExpectedException action=add>" + ex + "</ExpectedException>";
}
public void remove() {
SerializableRunnable removeRunnable = new SerializableRunnable(
"removeExpectedExceptions") {
public void run() {
final String remove = getRemoveString();
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) {
sys.getLogWriter().info(remove);
}
try {
getLogWriter().info(remove);
} catch (Exception noHydraLogger) {
}
logger.info(remove);
}
};
if (this.v != null) {
v.invoke(removeRunnable);
}
else {
invokeInEveryVM(removeRunnable);
}
String s = getRemoveString();
LogManager.getLogger(LogService.BASE_LOGGER_NAME).info(s);
// log it locally
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) { // avoid creating a system
sys.getLogWriter().info(s);
}
getLogWriter().info(s);
}
}
/**
* Log in all VMs, in both the test logger and the GemFire logger the
* expected exception string to prevent grep logs from complaining. The
* expected string is used by the GrepLogs utility and so can contain
* regular expression characters.
*
* If you do not remove the expected exception, it will be removed at the
* end of your test case automatically.
*
* @since 5.7bugfix
* @param exception
* the exception string to expect
* @return an ExpectedException instance for removal
*/
public static ExpectedException addExpectedException(final String exception) {
return addExpectedException(exception, null);
}
/**
* Log in all VMs, in both the test logger and the GemFire logger the
* expected exception string to prevent grep logs from complaining. The
* expected string is used by the GrepLogs utility and so can contain
* regular expression characters.
*
* @since 5.7bugfix
* @param exception
* the exception string to expect
* @param v
* the VM on which to log the expected exception or null for all VMs
* @return an ExpectedException instance for removal purposes
*/
public static ExpectedException addExpectedException(final String exception,
VM v) {
final ExpectedException ret;
if (v != null) {
ret = new ExpectedException(exception, v);
}
else {
ret = new ExpectedException(exception);
}
// define the add and remove expected exceptions
final String add = ret.getAddString();
SerializableRunnable addRunnable = new SerializableRunnable(
"addExpectedExceptions") {
public void run() {
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) {
sys.getLogWriter().info(add);
}
try {
getLogWriter().info(add);
} catch (Exception noHydraLogger) {
}
logger.info(add);
}
};
if (v != null) {
v.invoke(addRunnable);
}
else {
invokeInEveryVM(addRunnable);
}
LogManager.getLogger(LogService.BASE_LOGGER_NAME).info(add);
// Log it locally too
final InternalDistributedSystem sys = InternalDistributedSystem
.getConnectedInstance();
if (sys != null) { // avoid creating a cache
sys.getLogWriter().info(add);
}
getLogWriter().info(add);
expectedExceptions.add(ret);
return ret;
}
/**
* delete locator state files. Use this after getting a random port
* to ensure that an old locator state file isn't picked up by the
* new locator you're starting.
* @param ports
*/
public void deleteLocatorStateFile(int... ports) {
for (int i=0; i<ports.length; i++) {
File stateFile = new File("locator"+ports[i]+"view.dat");
if (stateFile.exists()) {
stateFile.delete();
}
}
}
}
|
GEODE-715: Fix import that was broken in merge to develop
|
gemfire-core/src/test/java/dunit/DistributedTestCase.java
|
GEODE-715: Fix import that was broken in merge to develop
|
<ide><path>emfire-core/src/test/java/dunit/DistributedTestCase.java
<ide> import com.gemstone.gemfire.internal.logging.log4j.LogWriterLogger;
<ide> import com.gemstone.gemfire.management.internal.cli.LogWrapper;
<ide> import com.gemstone.gemfire.test.junit.categories.DistributedTest;
<del>
<del>import dunit.standalone.DUnitLauncher;
<add>import com.gemstone.gemfire.test.dunit.standalone.DUnitLauncher;
<ide>
<ide> /**
<ide> * This class is the superclass of all distributed unit tests.
|
|
JavaScript
|
mit
|
1bcb4a4f0bbbd0f82ca3fb83f4c604900b791eed
| 0 |
dinchak/node-serialosc,dinchak/node-serialosc
|
/**
* @module node-serialosc
* @author Tom Dinchak <[email protected]>
*/
var _ = require('underscore');
var OscEmitter = require('osc-emitter');
var OscReceiver = require('osc-receiver');
var EventEmitter = require('events').EventEmitter;
/**
* A Device represents either an arc or a grid connected to serialosc
*
* The following properties can be passed as options or will be provided
* by serialosc as the result of a /sys/info call.
*
* host - the hostname to listen on (default: localhost)
* port - the port to listen on (default: random between 1024-65535)
* id - The id of the device (ie. m128-302, provided by serialosc)
* type - The type of device, grid or arc
* model - The model of device (ie. monome 128, provided by serialosc)
* deviceHost - the hostname the device is listening on (ie. localhost, provided by serialosc)
* devicePort - the port the device is listening on (ie. 38717, provided by serialosc)
* sizeX - the width of a grid device (ie. 16)
* sizeY - the height of a grid device (ie. 8)
* encoders - the number of encoders for an arc device (ie. 4)
* prefix - the prefix of the device (ie. /monome)
* connected - true after device is ready to use
*
* @constructor
*/
function Device() {}
/**
* Extend the EventEmitter prototype
* Provides .on(), .emit(), etc.
*/
Device.prototype = Object.create(EventEmitter.prototype);
/**
* Configure device
* @param {Object} opts configuration options
*/
Device.prototype.config = function (opts) {
// choose a random port if none is provided
this.port = opts.port || Math.floor(Math.random() * (65536 - 1024)) + 1024;
this.oscReceiver = new OscReceiver();
this.oscEmitter = new OscEmitter();
this.on = this.oscReceiver.on;
this.connected = false;
// set all keys passed in opts
for (var key in opts) {
this[key] = opts[key];
}
};
/**
* Begin listening on a host/port to respond to device messages
* Setup listeners for /sys messages
* Set the device's port and hostname
* Send /sys/info to get device information
*/
Device.prototype.start = function () {
var initMsgs = [
'/sys/host',
'/sys/port',
'/sys/prefix',
'/sys/rotation',
'/sys/size',
];
// listen on host/port to respond to device messages
this.oscReceiver.bind(this.port, this.host);
var self = this;
function receiveInitMsg(msg) {
if (self.connected) {
return;
}
initMsgs = _.without(initMsgs, msg);
if (initMsgs.length === 0) {
self.connected = true;
self.emit('initialized');
}
}
// handle basic /sys messages by setting device properties
this.oscReceiver.on('/sys/id', function () {
self.id = arguments[0];
});
this.oscReceiver.on('/sys/size', function () {
self.sizeX = arguments[0];
self.sizeY = arguments[1];
receiveInitMsg('/sys/size');
});
this.oscReceiver.on('/sys/rotation', function () {
self.rotation = arguments[0];
receiveInitMsg('/sys/rotation');
});
this.oscReceiver.on('/sys/connect', function () {
self.connected = true;
self.emit('connected');
});
this.oscReceiver.on('/sys/disconnect', function () {
self.connected = false;
self.emit('disconnected');
});
// device initialization is handled through these responders
// we wait for a response from /sys/port, /sys/host, and /sys/rotation
// before broadcasting the connected event
this.oscReceiver.on('/sys/port', function () {
self.port = arguments[0];
receiveInitMsg('/sys/port');
});
this.oscReceiver.on('/sys/host', function () {
self.host = arguments[0];
receiveInitMsg('/sys/host');
});
this.oscReceiver.on('/sys/prefix', function () {
// remove existing listeners for old prefix
self.removeListeners();
self.prefix = arguments[0];
// add new listeners for new prefix
self.addListeners();
receiveInitMsg('/sys/prefix');
});
// add deviceHost and devicePort to the broadcast list
this.oscEmitter.add(this.deviceHost, this.devicePort);
// initialize device
this.oscEmitter.emit(
'/sys/port',
{
type: 'integer',
value: this.port
}
);
this.oscEmitter.emit(
'/sys/host',
{
type: 'string',
value: self.host
}
);
this.oscEmitter.emit('/sys/info');
};
/**
* Called when the device is unplugged
*/
Device.prototype.stop = function () {
this.connected = false;
};
/**
* Sets a device's rotation
* @param {Number} r new rotation value (0, 90, 180, 270)
*/
Device.prototype.setRotation = function (r) {
this.oscEmitter.emit(
'/sys/rotation',
{
type: 'integer',
value: r
}
);
};
module.exports = Device;
|
lib/device.js
|
/**
* @module node-serialosc
* @author Tom Dinchak <[email protected]>
*/
var _ = require('underscore');
var OscEmitter = require('osc-emitter');
var OscReceiver = require('osc-receiver');
var EventEmitter = require('events').EventEmitter;
/**
* A Device represents either an arc or a grid connected to serialosc
*
* The following properties can be passed as options or will be provided
* by serialosc as the result of a /sys/info call.
*
* host - the hostname to listen on (default: localhost)
* port - the port to listen on (default: random between 1024-65535)
* id - The id of the device (ie. m128-302, provided by serialosc)
* type - The type of device, grid or arc
* model - The model of device (ie. monome 128, provided by serialosc)
* deviceHost - the hostname the device is listening on (ie. localhost, provided by serialosc)
* devicePort - the port the device is listening on (ie. 38717, provided by serialosc)
* sizeX - the width of a grid device (ie. 16)
* sizeY - the height of a grid device (ie. 8)
* encoders - the number of encoders for an arc device (ie. 4)
* prefix - the prefix of the device (ie. /monome)
* connected - true after device is ready to use
*
* @constructor
*/
function Device() {}
/**
* Extend the EventEmitter prototype
* Provides .on(), .emit(), etc.
*/
Device.prototype = Object.create(EventEmitter.prototype);
/**
* Configure device
* @param {Object} opts [description]
*/
Device.prototype.config = function (opts) {
// choose a random port if none is provided
this.port = opts.port || Math.floor(Math.random() * (65536 - 1024)) + 1024;
this.oscReceiver = new OscReceiver();
this.oscEmitter = new OscEmitter();
this.on = this.oscReceiver.on;
this.connected = false;
// set all keys passed in opts
for (var key in opts) {
this[key] = opts[key];
}
};
/**
* Begin listening on a host/port to respond to device messages
* Setup listeners for /sys messages
* Set the device's port and hostname
* Send /sys/info to get device information
*/
Device.prototype.start = function () {
var initMsgs = [
'/sys/host',
'/sys/port',
'/sys/prefix',
'/sys/rotation',
'/sys/size',
];
// listen on host/port to respond to device messages
this.oscReceiver.bind(this.port, this.host);
var self = this;
function receiveInitMsg(msg) {
if (self.connected) {
return;
}
initMsgs = _.without(initMsgs, msg);
if (initMsgs.length === 0) {
self.connected = true;
self.emit('initialized');
}
}
// handle basic /sys messages by setting device properties
this.oscReceiver.on('/sys/id', function () {
self.id = arguments[0];
});
this.oscReceiver.on('/sys/size', function () {
self.sizeX = arguments[0];
self.sizeY = arguments[1];
receiveInitMsg('/sys/size');
});
this.oscReceiver.on('/sys/rotation', function () {
self.rotation = arguments[0];
receiveInitMsg('/sys/rotation');
});
this.oscReceiver.on('/sys/connect', function () {
self.connected = true;
self.emit('connected');
});
this.oscReceiver.on('/sys/disconnect', function () {
self.connected = false;
self.emit('disconnected');
});
// device initialization is handled through these responders
// we wait for a response from /sys/port, /sys/host, and /sys/rotation
// before broadcasting the connected event
this.oscReceiver.on('/sys/port', function () {
self.port = arguments[0];
receiveInitMsg('/sys/port');
});
this.oscReceiver.on('/sys/host', function () {
self.host = arguments[0];
receiveInitMsg('/sys/host');
});
this.oscReceiver.on('/sys/prefix', function () {
// remove existing listeners for old prefix
self.removeListeners();
self.prefix = arguments[0];
// add new listeners for new prefix
self.addListeners();
receiveInitMsg('/sys/prefix');
});
// add deviceHost and devicePort to the broadcast list
this.oscEmitter.add(this.deviceHost, this.devicePort);
// initialize device
this.oscEmitter.emit(
'/sys/port',
{
type: 'integer',
value: this.port
}
);
this.oscEmitter.emit(
'/sys/host',
{
type: 'string',
value: self.host
}
);
this.oscEmitter.emit('/sys/info');
};
/**
* Called when the device is unplugged
*/
Device.prototype.stop = function () {
this.connected = false;
};
/**
* Sets a device's rotation
* @param {Number} r new rotation value (0, 90, 180, 270)
*/
Device.prototype.setRotation = function (r) {
this.oscEmitter.emit(
'/sys/rotation',
{
type: 'integer',
value: r
}
);
};
module.exports = Device;
|
jsdoc update
|
lib/device.js
|
jsdoc update
|
<ide><path>ib/device.js
<ide>
<ide> /**
<ide> * Configure device
<del> * @param {Object} opts [description]
<add> * @param {Object} opts configuration options
<ide> */
<ide> Device.prototype.config = function (opts) {
<ide> // choose a random port if none is provided
|
|
Java
|
agpl-3.0
|
4d26f781f60aec964827d56823acbf5e814df737
| 0 |
o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa
|
package com.x.base.core.project.cache;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.connection.CipherConnectionAction;
import com.x.base.core.project.jaxrs.WrapClearCacheRequest;
import com.x.base.core.project.tools.ListTools;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
@SuppressWarnings("unchecked")
public class ApplicationCache extends AbstractApplicationCache {
private NotifyThread notifyThread;
private ReceiveThread receiveThread;
private volatile static ApplicationCache INSTANCE;
private CacheManager manager;
private static Integer defaultSize = 1000;
private static Integer defaultTimeToIdle = MINUTES_20;
private static Integer defaultTimeToLive = MINUTES_30;
private static String SPLIT = "#";
public static String concreteCacheKey(Object... os) {
return StringUtils.join(os, SPLIT);
}
public <T extends JpaObject> Ehcache getCache(Class<T> clz, Integer cacheSize, Integer timeToIdle,
Integer timeToLive) {
return this.getCache(clz.getName(), cacheSize, timeToIdle, timeToLive);
}
public <T extends JpaObject> Ehcache getCache(Class<T> clz) {
return this.getCache(clz.getName(), defaultSize, defaultTimeToIdle, defaultTimeToLive);
}
public Ehcache getCache(Class<?>... classes) {
List<String> classNames = new ArrayList<>();
for (Class<?> clz : classes) {
classNames.add(clz.getName());
}
return this.getCache(StringUtils.join(classNames, SPLIT), defaultSize, defaultTimeToIdle, defaultTimeToLive);
}
private Ehcache getCache(String name) {
return this.getCache(name, defaultSize, defaultTimeToIdle, defaultTimeToLive);
}
public <T extends JpaObject> Element get(Class<T> clz, String key) {
return this.getCache(clz).get(key);
}
public <T extends JpaObject> void put(Class<T> clz, String key, Object value) {
this.getCache(clz).put(new Element(key, value));
}
public void put(String key, Object value, Class<? extends JpaObject>... classes) {
this.getCache(classes).put(new Element(key, value));
}
public static <T extends JpaObject> void notify(Class<T> clz) throws Exception {
List<Object> list = new ArrayList<>();
notify(clz, list);
}
public static <T extends JpaObject> void notify(Class<T> clz, Object... objects) throws Exception {
List<Object> list = new ArrayList<>();
for (Object o : objects) {
list.add(o);
}
notify(clz, list);
}
public static <T extends JpaObject> void notify(Class<T> clz, List<Object> keys) throws Exception {
ClearCacheRequest req = new ClearCacheRequest();
req.setClassName(clz.getName());
req.setKeys(keys);
instance().NotifyQueue.put(req);
}
public static <T extends JpaObject> void receive(WrapClearCacheRequest wi) throws Exception {
instance().ReceiveQueue.put(wi);
}
public Ehcache getCache(String name, Integer cacheSize, Integer timeToIdle, Integer timeToLive) {
Ehcache cache = manager.getCache(name);
if (null != cache) {
return cache;
} else {
synchronized (ApplicationCache.class) {
cache = manager.getCache(name);
if (null == cache) {
cache = new Cache(cacheConfiguration(name, cacheSize, timeToIdle, timeToLive));
manager.addCache(cache);
}
}
}
return cache;
}
private ApplicationCache() {
try {
manager = createCacheManager();
this.notifyThread = new NotifyThread();
notifyThread.start();
this.receiveThread = new ReceiveThread();
receiveThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static ApplicationCache instance() {
if (INSTANCE == null) {
synchronized (ApplicationCache.class) {
if (INSTANCE == null) {
INSTANCE = new ApplicationCache();
}
}
}
return INSTANCE;
}
public static void shutdown() {
if (INSTANCE != null) {
synchronized (ApplicationCache.class) {
try {
INSTANCE.ReceiveQueue.put(new StopReceiveThreadSignal());
INSTANCE.NotifyQueue.put(new StopNotifyThreadSignal());
INSTANCE.manager.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void clear() {
if (INSTANCE != null) {
synchronized (ApplicationCache.class) {
INSTANCE.manager.clearAll();
}
}
}
public class NotifyThread extends Thread {
public void run() {
out: while (true) {
try {
WrapClearCacheRequest wi = NotifyQueue.take();
if (wi instanceof StopNotifyThreadSignal) {
break out;
} else {
String url = Config.url_x_program_center_jaxrs("cachedispatch");
CipherConnectionAction.put(false, url, wi);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ApplicationCache NotifyThread stoped!");
}
}
public class ReceiveThread extends Thread {
public void run() {
out: while (true) {
try {
WrapClearCacheRequest wi = ReceiveQueue.take();
if (wi instanceof StopReceiveThreadSignal) {
break out;
}
for (String str : INSTANCE.manager.getCacheNames()) {
/** 缓存名可能由多组组成 */
if (ArrayUtils.contains(StringUtils.split(str, SPLIT), wi.getClassName())) {
Ehcache cache = INSTANCE.getCache(str);
List<Object> keys = wi.getKeys();
if (ListTools.isNotEmpty(keys)) {
/** 根据给定的关键字进行删除 */
List<Object> removes = new ArrayList<>();
for (Object key : keys) {
for (Object o : cache.getKeys()) {
if (Objects.equals(o, key)) {
removes.add(o);
}
if (StringUtils.startsWith(o.toString(), key + SPLIT)) {
removes.add(o);
}
}
}
if (!removes.isEmpty()) {
cache.removeAll(removes);
}
} else {
cache.removeAll();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ApplicationCache ReceiveThread stoped!");
}
}
public String generateKey(Object... objects) {
List<String> list = new ArrayList<>();
for (Object o : objects) {
list.add(Objects.toString(o, ""));
}
return StringUtils.join(list, SPLIT);
}
public static class ClearCacheRequest extends WrapClearCacheRequest {
}
}
|
o2server/x_base_core_project/src/main/java/com/x/base/core/project/cache/ApplicationCache.java
|
package com.x.base.core.project.cache;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.connection.CipherConnectionAction;
import com.x.base.core.project.jaxrs.WrapClearCacheRequest;
import com.x.base.core.project.tools.ListTools;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
@SuppressWarnings("unchecked")
public class ApplicationCache111 extends AbstractApplicationCache {
private NotifyThread notifyThread;
private ReceiveThread receiveThread;
private volatile static ApplicationCache INSTANCE;
private CacheManager manager;
private static Integer defaultSize = 1000;
private static Integer defaultTimeToIdle = MINUTES_20;
private static Integer defaultTimeToLive = MINUTES_30;
private static String SPLIT = "#";
public static String concreteCacheKey(Object... os) {
return StringUtils.join(os, SPLIT);
}
public <T extends JpaObject> Ehcache getCache(Class<T> clz, Integer cacheSize, Integer timeToIdle,
Integer timeToLive) {
return this.getCache(clz.getName(), cacheSize, timeToIdle, timeToLive);
}
public <T extends JpaObject> Ehcache getCache(Class<T> clz) {
return this.getCache(clz.getName(), defaultSize, defaultTimeToIdle, defaultTimeToLive);
}
public Ehcache getCache(Class<?>... classes) {
List<String> classNames = new ArrayList<>();
for (Class<?> clz : classes) {
classNames.add(clz.getName());
}
return this.getCache(StringUtils.join(classNames, SPLIT), defaultSize, defaultTimeToIdle, defaultTimeToLive);
}
private Ehcache getCache(String name) {
return this.getCache(name, defaultSize, defaultTimeToIdle, defaultTimeToLive);
}
public <T extends JpaObject> Element get(Class<T> clz, String key) {
return this.getCache(clz).get(key);
}
public <T extends JpaObject> void put(Class<T> clz, String key, Object value) {
this.getCache(clz).put(new Element(key, value));
}
public void put(String key, Object value, Class<? extends JpaObject>... classes) {
this.getCache(classes).put(new Element(key, value));
}
public static <T extends JpaObject> void notify(Class<T> clz) throws Exception {
List<Object> list = new ArrayList<>();
notify(clz, list);
}
public static <T extends JpaObject> void notify(Class<T> clz, Object... objects) throws Exception {
List<Object> list = new ArrayList<>();
for (Object o : objects) {
list.add(o);
}
notify(clz, list);
}
public static <T extends JpaObject> void notify(Class<T> clz, List<Object> keys) throws Exception {
ClearCacheRequest req = new ClearCacheRequest();
req.setClassName(clz.getName());
req.setKeys(keys);
instance().NotifyQueue.put(req);
}
public static <T extends JpaObject> void receive(WrapClearCacheRequest wi) throws Exception {
instance().ReceiveQueue.put(wi);
}
public Ehcache getCache(String name, Integer cacheSize, Integer timeToIdle, Integer timeToLive) {
Ehcache cache = manager.getCache(name);
if (null != cache) {
return cache;
} else {
synchronized (ApplicationCache.class) {
cache = manager.getCache(name);
if (null == cache) {
cache = new Cache(cacheConfiguration(name, cacheSize, timeToIdle, timeToLive));
manager.addCache(cache);
}
}
}
return cache;
}
private ApplicationCache() {
try {
manager = createCacheManager();
this.notifyThread = new NotifyThread();
notifyThread.start();
this.receiveThread = new ReceiveThread();
receiveThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static ApplicationCache instance() {
if (INSTANCE == null) {
synchronized (ApplicationCache.class) {
if (INSTANCE == null) {
INSTANCE = new ApplicationCache();
}
}
}
return INSTANCE;
}
public static void shutdown() {
if (INSTANCE != null) {
synchronized (ApplicationCache.class) {
try {
INSTANCE.ReceiveQueue.put(new StopReceiveThreadSignal());
INSTANCE.NotifyQueue.put(new StopNotifyThreadSignal());
INSTANCE.manager.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void clear() {
if (INSTANCE != null) {
synchronized (ApplicationCache.class) {
INSTANCE.manager.clearAll();
}
}
}
public class NotifyThread extends Thread {
public void run() {
out: while (true) {
try {
WrapClearCacheRequest wi = NotifyQueue.take();
if (wi instanceof StopNotifyThreadSignal) {
break out;
} else {
String url = Config.url_x_program_center_jaxrs("cachedispatch");
CipherConnectionAction.put(false, url, wi);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ApplicationCache NotifyThread stoped!");
}
}
public class ReceiveThread extends Thread {
public void run() {
out: while (true) {
try {
WrapClearCacheRequest wi = ReceiveQueue.take();
if (wi instanceof StopReceiveThreadSignal) {
break out;
}
for (String str : INSTANCE.manager.getCacheNames()) {
/** 缓存名可能由多组组成 */
if (ArrayUtils.contains(StringUtils.split(str, SPLIT), wi.getClassName())) {
Ehcache cache = INSTANCE.getCache(str);
List<Object> keys = wi.getKeys();
if (ListTools.isNotEmpty(keys)) {
/** 根据给定的关键字进行删除 */
List<Object> removes = new ArrayList<>();
for (Object key : keys) {
for (Object o : cache.getKeys()) {
if (Objects.equals(o, key)) {
removes.add(o);
}
if (StringUtils.startsWith(o.toString(), key + SPLIT)) {
removes.add(o);
}
}
}
if (!removes.isEmpty()) {
cache.removeAll(removes);
}
} else {
cache.removeAll();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ApplicationCache ReceiveThread stoped!");
}
}
public String generateKey(Object... objects) {
List<String> list = new ArrayList<>();
for (Object o : objects) {
list.add(Objects.toString(o, ""));
}
return StringUtils.join(list, SPLIT);
}
public static class ClearCacheRequest extends WrapClearCacheRequest {
}
}
|
fixApplicationCache
|
o2server/x_base_core_project/src/main/java/com/x/base/core/project/cache/ApplicationCache.java
|
fixApplicationCache
|
<ide><path>2server/x_base_core_project/src/main/java/com/x/base/core/project/cache/ApplicationCache.java
<ide> import net.sf.ehcache.Element;
<ide>
<ide> @SuppressWarnings("unchecked")
<del>public class ApplicationCache111 extends AbstractApplicationCache {
<add>public class ApplicationCache extends AbstractApplicationCache {
<ide>
<ide> private NotifyThread notifyThread;
<ide> private ReceiveThread receiveThread;
|
|
Java
|
mit
|
error: pathspec 'src/main/java/leetcode/Problem146.java' did not match any file(s) known to git
|
c488ba98279d5705f06c3288107e9e4a51779cd9
| 1 |
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
|
package leetcode;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* https://leetcode.com/problems/lru-cache/
*/
public class Problem146 {
public static class LRUCache {
private final Map<Integer, Integer> map = new HashMap<>();
private final LinkedList<Integer> list = new LinkedList<>();
private final int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (map.containsKey(key)) {
list.addLast(key);
list.removeFirst();
}
return map.getOrDefault(key, -1);
}
public void set(int key, int value) {
if (!map.containsKey(key)) {
list.addLast(key);
}
map.put(key, value);
if (map.size() -1 == capacity) {
int removedKey = list.removeFirst();
map.remove(removedKey);
}
}
}
public static void main(String[] args) {
LRUCache lru = new LRUCache(2);
// lru.set(2, 1);
// lru.set(1, 1);
// System.out.println(lru.get(2)); // 1
// lru.set(4, 1);
// System.out.println(lru.get(1)); // -1
// System.out.println(lru.get(2)); // 1
// lru.set(5, 1);
// lru.set(6, 1);
// System.out.println(lru.get(1)); // -1
// System.out.println(lru.get(2)); // -1
// System.out.println(lru.get(3)); // -1
// System.out.println(lru.get(4)); // -1
// System.out.println(lru.get(5)); // 1
// System.out.println(lru.get(6)); // 1
lru.set(2, 1);
System.out.println("1. " + lru.map);
System.out.println("1. " + lru.list);
lru.set(1, 1);
System.out.println("2. " + lru.map);
System.out.println("2. " + lru.list);
lru.set(2, 3);
System.out.println("3. " + lru.map);
System.out.println("3. " + lru.list);
lru.set(4, 1);
System.out.println("4. " + lru.map);
System.out.println("4. " + lru.list);
System.out.println(lru.get(1)); // -1
System.out.println(lru.get(2)); // 3
System.out.println("5. " + lru.map);
System.out.println("5. " + lru.list);
}
}
|
src/main/java/leetcode/Problem146.java
|
Create a skeleton for problem 146
|
src/main/java/leetcode/Problem146.java
|
Create a skeleton for problem 146
|
<ide><path>rc/main/java/leetcode/Problem146.java
<add>package leetcode;
<add>
<add>import java.util.HashMap;
<add>import java.util.LinkedList;
<add>import java.util.Map;
<add>
<add>/**
<add> * https://leetcode.com/problems/lru-cache/
<add> */
<add>public class Problem146 {
<add> public static class LRUCache {
<add> private final Map<Integer, Integer> map = new HashMap<>();
<add> private final LinkedList<Integer> list = new LinkedList<>();
<add> private final int capacity;
<add>
<add> public LRUCache(int capacity) {
<add> this.capacity = capacity;
<add> }
<add>
<add> public int get(int key) {
<add> if (map.containsKey(key)) {
<add> list.addLast(key);
<add> list.removeFirst();
<add> }
<add> return map.getOrDefault(key, -1);
<add> }
<add>
<add> public void set(int key, int value) {
<add> if (!map.containsKey(key)) {
<add> list.addLast(key);
<add> }
<add> map.put(key, value);
<add> if (map.size() -1 == capacity) {
<add> int removedKey = list.removeFirst();
<add> map.remove(removedKey);
<add> }
<add> }
<add> }
<add>
<add> public static void main(String[] args) {
<add> LRUCache lru = new LRUCache(2);
<add>// lru.set(2, 1);
<add>// lru.set(1, 1);
<add>// System.out.println(lru.get(2)); // 1
<add>// lru.set(4, 1);
<add>// System.out.println(lru.get(1)); // -1
<add>// System.out.println(lru.get(2)); // 1
<add>// lru.set(5, 1);
<add>// lru.set(6, 1);
<add>// System.out.println(lru.get(1)); // -1
<add>// System.out.println(lru.get(2)); // -1
<add>// System.out.println(lru.get(3)); // -1
<add>// System.out.println(lru.get(4)); // -1
<add>// System.out.println(lru.get(5)); // 1
<add>// System.out.println(lru.get(6)); // 1
<add>
<add> lru.set(2, 1);
<add> System.out.println("1. " + lru.map);
<add> System.out.println("1. " + lru.list);
<add> lru.set(1, 1);
<add> System.out.println("2. " + lru.map);
<add> System.out.println("2. " + lru.list);
<add> lru.set(2, 3);
<add> System.out.println("3. " + lru.map);
<add> System.out.println("3. " + lru.list);
<add> lru.set(4, 1);
<add> System.out.println("4. " + lru.map);
<add> System.out.println("4. " + lru.list);
<add> System.out.println(lru.get(1)); // -1
<add> System.out.println(lru.get(2)); // 3
<add> System.out.println("5. " + lru.map);
<add> System.out.println("5. " + lru.list);
<add> }
<add>}
|
|
Java
|
mit
|
c7f9a6728c1c151bfe1ebb5b4da986d6370229e0
| 0 |
defunct/cafe
|
package com.goodworkalan.mix;
import java.util.ArrayList;
import java.util.List;
import com.goodworkalan.go.go.Artifact;
public class BasicJavaModule extends ProjectModule {
private final List<Artifact> dependencies = new ArrayList<Artifact>();
private final List<Artifact> testDepenencies = new ArrayList<Artifact>();
private final Artifact produces;
public BasicJavaModule(Artifact produces) {
this.produces = produces;
}
public void addDependency(Artifact artifact) {
dependencies.add(artifact);
}
public void addTestDependency(Artifact artifact) {
testDepenencies.add(artifact);
}
@Override
public void build(Builder builder) {
RecipeElement recipe = builder.recipe("javac");
DependsElement depends = recipe.depends();
for (Artifact artifact : dependencies) {
depends.artifact(artifact.getGroup(), artifact.getName(), artifact.getVersion());
}
depends.end();
recipe
.command("javac")
.argument("source-directory", "src/main/java")
.argument("output-directory", "smotchkiss/classes")
.argument("debug", "true")
.end()
.command("copy")
.argument("source-directory", "src/main/resources")
.argument("output-directory", "smotchkiss/classes")
.end()
.produces()
.classes("smotchkiss/classes")
.end()
.end();
recipe = builder.recipe("javac-test");
depends = recipe.depends();
depends.source("javac");
for (Artifact artifact : testDepenencies) {
depends.artifact(artifact.getGroup(), artifact.getName(), artifact.getVersion());
}
depends.end();
recipe
.command("javac")
.argument("source-directory", "src/test/java")
.argument("output-directory", "smotchkiss/test-classes")
.argument("debug", "true")
.end()
.produces()
.classes("smotchkiss/test-classes")
.end()
.end();
builder
.recipe("test")
.depends()
.source("javac-test")
.end()
.command("test-ng")
.argument("source-directory", "src/test/java")
.end()
.end()
.recipe("clean")
.command("delete")
.argument("file", "smotchkiss")
.argument("recurse", "true")
.end()
.end()
.recipe("distribution")
.depends()
.source("javac")
.end()
.command("delete")
.argument("file", "smotchkiss/distribution")
.argument("recurse", "true")
.end()
.command("mkdirs")
.argument("directory", "smotchkiss/distribution/com/goodworkalan/mix/0.1")
.end()
.command("dependencies")
.argument("output-file", "smotchkiss/distribution/" + produces.getPath("", "dep"))
.end()
.command("zip")
.argument("source-directory", "smotchkiss/classes")
.argument("level", "0")
.argument("output-file", "smotchkiss/distribution/" + produces.getPath("", "jar"))
.end()
.produces()
.artifact(produces.getGroup(), produces.getName(), produces.getVersion()).in("smotchkiss/distribution")
.end()
.end()
.end();
}
}
|
src/main/java/com/goodworkalan/mix/BasicJavaModule.java
|
package com.goodworkalan.mix;
import java.util.ArrayList;
import java.util.List;
import com.goodworkalan.go.go.Artifact;
public class BasicJavaModule extends ProjectModule {
private final List<Artifact> dependencies = new ArrayList<Artifact>();
private final List<Artifact> testDepenencies = new ArrayList<Artifact>();
private final Artifact produces;
public BasicJavaModule(Artifact produces) {
this.produces = produces;
}
public void addDependency(Artifact artifact) {
dependencies.add(artifact);
}
public void addTestDependency(Artifact artifact) {
testDepenencies.add(artifact);
}
@Override
public void build(Builder builder) {
RecipeElement recipe = builder.recipe("javac");
DependsElement depends = recipe.depends();
for (Artifact artifact : dependencies) {
depends.artifact(artifact.getGroup(), artifact.getName(), artifact.getVersion());
}
depends.end();
recipe
.command("javac")
.argument("source-directory", "src/main/java")
.argument("output-directory", "smotchkiss/classes")
.argument("debug", "true")
.end()
.command("copy")
.argument("source-directory", "src/main/resources")
.argument("output-directory", "smotchkiss/classes")
.end()
.produces()
.classes("smotchkiss/classes")
.end()
.end();
recipe = builder.recipe("javac-test");
depends = recipe.depends();
for (Artifact artifact : testDepenencies) {
depends.artifact(artifact.getGroup(), artifact.getName(), artifact.getVersion());
}
depends.end();
recipe
.command("javac")
.argument("source-directory", "src/test/java")
.argument("output-directory", "smotchkiss/test-classes")
.argument("debug", "true")
.end()
.produces()
.classes("smotchkiss/test-classes")
.end()
.end();
builder
.recipe("test")
.depends()
.source("javac-test")
.end()
.command("test-ng")
.argument("source-directory", "src/test/java")
.end()
.end()
.recipe("clean")
.command("delete")
.argument("file", "smotchkiss")
.argument("recurse", "true")
.end()
.end()
.recipe("distribution")
.depends()
.source("javac")
.end()
.command("delete")
.argument("file", "smotchkiss/distribution")
.argument("recurse", "true")
.end()
.command("mkdirs")
.argument("directory", "smotchkiss/distribution/com/goodworkalan/mix/0.1")
.end()
.command("dependencies")
.argument("output-file", "smotchkiss/distribution/" + produces.getPath("", "dep"))
.end()
.command("zip")
.argument("source-directory", "smotchkiss/classes")
.argument("level", "0")
.argument("output-file", "smotchkiss/distribution/" + produces.getPath("", "jar"))
.end()
.produces()
.artifact(produces.getGroup(), produces.getName(), produces.getVersion()).in("smotchkiss/distribution")
.end()
.end()
.end();
}
}
|
Fixed testing in basic Java module.
|
src/main/java/com/goodworkalan/mix/BasicJavaModule.java
|
Fixed testing in basic Java module.
|
<ide><path>rc/main/java/com/goodworkalan/mix/BasicJavaModule.java
<ide> .end();
<ide> recipe = builder.recipe("javac-test");
<ide> depends = recipe.depends();
<add> depends.source("javac");
<ide> for (Artifact artifact : testDepenencies) {
<ide> depends.artifact(artifact.getGroup(), artifact.getName(), artifact.getVersion());
<ide> }
|
|
Java
|
agpl-3.0
|
69155d6936fb34da26b7e3e52e8ec58b792b4ee5
| 0 |
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
f5acc378-2e61-11e5-9284-b827eb9e62be
|
hello.java
|
f5a747fe-2e61-11e5-9284-b827eb9e62be
|
f5acc378-2e61-11e5-9284-b827eb9e62be
|
hello.java
|
f5acc378-2e61-11e5-9284-b827eb9e62be
|
<ide><path>ello.java
<del>f5a747fe-2e61-11e5-9284-b827eb9e62be
<add>f5acc378-2e61-11e5-9284-b827eb9e62be
|
|
Java
|
apache-2.0
|
df7a23724b8c8c641682fc383aaa119507b7a0b9
| 0 |
akshaymaniyar/dropwizard,edgarvonk/dropwizard,takecy/dropwizard,ojacobson/dropwizard,rgupta-okta/dropwizard,charlieg/dropwizard,kjetilv/dropwizard,yshaojie/dropwizard,wilko55/dropwizard,takecy/dropwizard,MikaelAmborn/dropwizard,xiaoping2367/dropwizard,tjcutajar/dropwizard,ryankennedy/dropwizard,StanSvec/dropwizard,tburch/dropwizard,ben1247/dropwizard,Trundle/dropwizard,aaanders/dropwizard,jelgh/dropwizard,douzzi/dropwizard,michelle-liang/dropwizard,MikaelAmborn/dropwizard,xiaoping2367/dropwizard,plausible-retired/warwizard,zhiqinghuang/dropwizard,arunsingh/dropwizard,mnrasul/dropwizard,micsta/dropwizard,pradex/dropwizard,nickbabcock/dropwizard,michelle-liang/dropwizard,evnm/dropwizard,phambryan/dropwizard,tiankong1986/dropwizard,pkwarren/dropwizard,puneetjaiswal/dropwizard,christophercurrie/dropwizard,jamesward/dropwizard,jamesward/dropwizard,philandstuff/dropwizard,yshaojie/dropwizard,cvent/dropwizard,calou/dropwizard,vforce/dropwizard,tiankong1986/dropwizard,ckingsbu/dropwizard,akraxx/dropwizard,sytolk/dropwizard,Randgalt/dropwizard,anonymint/dropwizard,dotCipher/dropwizard,tjcutajar/dropwizard,ptomli/dropwizard,AnuchitPrasertsang/dropwizard,carlo-rtr/dropwizard,tburch/dropwizard,tiankong1986/dropwizard,pkwarren/dropwizard,akraxx/dropwizard,bbrighttaer/dropwizard,amillalen/dropwizard,Alexey1Gavrilov/dropwizard,patrox/dropwizard,mtbigham/dropwizard,douzzi/dropwizard,plausible-retired/warwizard,dotCipher/dropwizard,flipsterkeshav/dropwizard,michelle-liang/dropwizard,vikasshinde22105/dropwizard,phambryan/dropwizard,ojacobson/dropwizard,dropwizard/dropwizard,hbrahi1/dropwizard,hancy2013/dropwizard,thomasandersen77/dropwizard,ckingsbu/dropwizard,dropwizard/dropwizard,taohaolong/dropwizard,carlo-rtr/dropwizard,mattnelson/dropwizard,puneetjaiswal/dropwizard,dsavinkov/dropwizard,zhiqinghuang/dropwizard,svenefftinge/dropwizard,dotCipher/dropwizard,amillalen/dropwizard,cvent/dropwizard,boundary/dropwizard,christophercurrie/dropwizard,boundary/dropwizard,grange74/dropwizard,qinfchen/dropwizard,mosoft521/dropwizard,rgupta-okta/dropwizard,ben1247/dropwizard,tjcutajar/dropwizard,nmharsha93/dropwizard,Randgalt/dropwizard,mtbigham/dropwizard,cvent/dropwizard,flipsterkeshav/dropwizard,randiroe/dropwizard,pkwarren/dropwizard,dsavinkov/dropwizard,chaminda204/dropwizard,ryankennedy/dropwizard,Alexey1Gavrilov/dropwizard,yshaojie/dropwizard,Trundle/dropwizard,jelgh/dropwizard,ryankennedy/dropwizard,amillalen/dropwizard,evnm/dropwizard,phouse512/dropwizard,biogerm/dropwizard,randiroe/dropwizard,bbrighttaer/dropwizard,nickbabcock/dropwizard,taohaolong/dropwizard,csae1152/dropwizard,wilko55/dropwizard,philandstuff/dropwizard,charlieg/dropwizard,phambryan/dropwizard,nmharsha93/dropwizard,bbrighttaer/dropwizard,wakandan/dropwizard,mulloymorrow/dropwizard,mosoft521/dropwizard,wakandan/dropwizard,chaminda204/dropwizard,wangcan2014/dropwizard,puneetjaiswal/dropwizard,akshaymaniyar/dropwizard,Toilal/dropwizard,taltmann/dropwizard,jplock/dropwizard,hbrahi1/dropwizard,thomasandersen77/dropwizard,shawnsmith/dropwizard,wilko55/dropwizard,calou/dropwizard,Alexey1Gavrilov/dropwizard,vforce/dropwizard,helt/dropwizard,chaminda204/dropwizard,aaanders/dropwizard,edgarvonk/dropwizard,hancy2013/dropwizard,nicktelford/dropwizard,flipsterkeshav/dropwizard,Toilal/dropwizard,kjetilv/dropwizard,shawnsmith/dropwizard,taltmann/dropwizard,tburch/dropwizard,mtbigham/dropwizard,hbrahi1/dropwizard,mnrasul/dropwizard,akraxx/dropwizard,kdave47/dropwizard,shawnsmith/dropwizard,randiroe/dropwizard,benearlam/dropwizard,evnm/dropwizard,takecy/dropwizard,AnuchitPrasertsang/dropwizard,ptomli/dropwizard,Randgalt/dropwizard,ajaiyen/dropwizard,wangcan2014/dropwizard,arunsingh/dropwizard,nmharsha93/dropwizard,StanSvec/dropwizard,mattnelson/dropwizard,AnuchitPrasertsang/dropwizard,nickbabcock/dropwizard,AnuchitPrasertsang/dropwizard,sridhar-newsdistill/dropwizard,philandstuff/dropwizard,kdave47/dropwizard,qinfchen/dropwizard,kjetilv/dropwizard,ptomli/dropwizard,Trundle/dropwizard,biogerm/dropwizard,svenefftinge/dropwizard,micsta/dropwizard,dropwizard/dropwizard,dsavinkov/dropwizard,charlieg/dropwizard,calou/dropwizard,jelgh/dropwizard,akshaymaniyar/dropwizard,patrox/dropwizard,helt/dropwizard,charlieg/dropwizard,anonymint/dropwizard,phouse512/dropwizard,carlo-rtr/dropwizard,helt/dropwizard,wakandan/dropwizard,wangcan2014/dropwizard,ajaiyen/dropwizard,csae1152/dropwizard,mulloymorrow/dropwizard,pradex/dropwizard,qinfchen/dropwizard,ckingsbu/dropwizard,aaanders/dropwizard,douzzi/dropwizard,grange74/dropwizard,kdave47/dropwizard,jplock/dropwizard,vikasshinde22105/dropwizard,nicktelford/dropwizard,thomasandersen77/dropwizard,taltmann/dropwizard,mosoft521/dropwizard,zhiqinghuang/dropwizard,mulloymorrow/dropwizard,hancy2013/dropwizard,phouse512/dropwizard,sytolk/dropwizard,christophercurrie/dropwizard,ojacobson/dropwizard,MikaelAmborn/dropwizard,patrox/dropwizard,arunsingh/dropwizard,StanSvec/dropwizard,csae1152/dropwizard,pradex/dropwizard,ben1247/dropwizard,edgarvonk/dropwizard,taohaolong/dropwizard,csae1152/dropwizard,vforce/dropwizard,xiaoping2367/dropwizard,ajaiyen/dropwizard,benearlam/dropwizard,jplock/dropwizard,sytolk/dropwizard,mnrasul/dropwizard,rgupta-okta/dropwizard,sridhar-newsdistill/dropwizard,biogerm/dropwizard,svenefftinge/dropwizard,mattnelson/dropwizard,vikasshinde22105/dropwizard,Toilal/dropwizard,micsta/dropwizard,benearlam/dropwizard,grange74/dropwizard,sridhar-newsdistill/dropwizard
|
package com.yammer.dropwizard.bundles;
import com.yammer.dropwizard.Bundle;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.servlets.AssetServlet;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A bundle for serving static asset files from the classpath.
*/
public class AssetsBundle implements Bundle {
public static final String DEFAULT_PATH = "/assets";
public static final int DEFAULT_MAX_CACHE_SIZE = 100;
private final String path;
private final int maxCacheSize;
/**
* Creates a new {@link AssetsBundle} which serves up static assets from
* {@code src/main/resources/assets/*} as {@code /assets/*}.
*
* @see AssetsBundle#AssetsBundle(String, int)
*/
public AssetsBundle() {
this(DEFAULT_PATH, DEFAULT_MAX_CACHE_SIZE);
}
/**
* Creates a new {@link AssetsBundle} which will configure the service to serve the static files
* located in {@code src/main/resources/${path}} as {@code /${path}}. For example, given a
* {@code path} of {@code "/assets"}, {@code src/main/resources/assets/example.js} would be
* served up from {@code /assets/example.js}.
*
* @param path the classpath and URI root of the static asset files
* @see AssetsBundle#AssetsBundle(String, int)
*/
public AssetsBundle(String path) {
this(path, DEFAULT_MAX_CACHE_SIZE);
}
/**
* Creates a new {@link AssetsBundle} which will configure the service to serve the static files
* located in {@code src/main/resources/${path}} as {@code /${path}}. For example, given a
* {@code path} of {@code "/assets"}, {@code src/main/resources/assets/example.js} would be
* served up from {@code /assets/example.js}.
*
* @param path the classpath and URI root of the static asset files
* @param maxCacheSize the maximum number of resources to cache
*/
public AssetsBundle(String path, int maxCacheSize) {
checkArgument(path.startsWith("/"), "%s is not an absolute path", path);
checkArgument(!"/".equals(path), "%s is the classpath root");
this.path = path.endsWith("/") ? path : (path + '/');
this.maxCacheSize = maxCacheSize;
}
@Override
public void initialize(Environment environment) {
environment.addServlet(new AssetServlet(path, maxCacheSize), path + '*');
}
}
|
dropwizard-core/src/main/java/com/yammer/dropwizard/bundles/AssetsBundle.java
|
package com.yammer.dropwizard.bundles;
import com.yammer.dropwizard.Bundle;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.servlets.AssetServlet;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A bundle for serving static asset files from the classpath.
*/
public class AssetsBundle implements Bundle {
public static final String DEFAULT_PATH = "/assets";
public static final int DEFAULT_MAX_CACHE_SIZE = 100;
private final String path;
private final int maxCacheSize;
/**
* Creates a new {@link AssetsBundle} which serves up static assets from
* {@code src/main/resources/assets/*} as {@code /assets/*}.
*
* @see AssetsBundle#AssetsBundle(String, int)
*/
public AssetsBundle() {
this(DEFAULT_PATH, DEFAULT_MAX_CACHE_SIZE);
}
/**
* Creates a new {@link AssetsBundle} which will configure the service to serve the static files
* located in {@code src/main/resources/${path}} as {@code /${path}}. For example, given a
* {@code path} of {@code "/assets"}, {@code src/main/resources/assets/example.js} would be
* served up from {@code /assets/example.js}.
*
* @param path the classpath and URI root of the static asset files
* @see AssetsBundle#AssetsBundle(String, int)
*/
public AssetsBundle(String path) {
this(path, DEFAULT_MAX_CACHE_SIZE);
}
/**
* Creates a new {@link AssetsBundle} which will configure the service to serve the static files
* located in {@code src/main/resources/${path}} as {@code /${path}}. For example, given a
* {@code path} of {@code "/assets"}, {@code src/main/resources/assets/example.js} would be
* served up from {@code /assets/example.js}.
*
* @param path the classpath and URI root of the static asset files
* @param maxCacheSize the maximum number of resources to cache
*/
public AssetsBundle(String path, int maxCacheSize) {
checkArgument(path.startsWith("/"), "%s is not an absolute path", path);
checkArgument(!"/".equals(path), "%s is the classpath root");
this.path = path.endsWith("/") ? path : (path + '/');
this.maxCacheSize = maxCacheSize;
}
@Override
public void initialize(Environment environment) {
environment.addServlet(new AssetServlet(path, maxCacheSize), path + '*');
}
}
|
Pretty up some Javadocs.
|
dropwizard-core/src/main/java/com/yammer/dropwizard/bundles/AssetsBundle.java
|
Pretty up some Javadocs.
|
<ide><path>ropwizard-core/src/main/java/com/yammer/dropwizard/bundles/AssetsBundle.java
<ide> * {@code path} of {@code "/assets"}, {@code src/main/resources/assets/example.js} would be
<ide> * served up from {@code /assets/example.js}.
<ide> *
<del> * @param path the classpath and URI root of the static asset files
<add> * @param path the classpath and URI root of the static asset files
<ide> * @see AssetsBundle#AssetsBundle(String, int)
<ide> */
<ide> public AssetsBundle(String path) {
|
|
JavaScript
|
agpl-3.0
|
46d007f6dfe14ca0ff0b611e738f181a840e2243
| 0 |
hitsumabushi/processmaker,baozhoutao/processmaker,colosa/processmaker,hitsumabushi/processmaker,tomolimo/processmaker-server,baozhoutao/processmaker,baozhoutao/processmaker,tomolimo/processmaker-server,hitsumabushi/processmaker,colosa/processmaker,tomolimo/processmaker-server,baozhoutao/processmaker,baozhoutao/processmaker,tomolimo/processmaker-server,colosa/processmaker,colosa/processmaker,tomolimo/processmaker-server,colosa/processmaker,hitsumabushi/processmaker,hitsumabushi/processmaker,tomolimo/processmaker-server,colosa/processmaker,baozhoutao/processmaker,hitsumabushi/processmaker
|
/**This notice must be untouched at all times.
This is the COMPRESSED version of the Draw2D Library
WebSite: http://www.draw2d.org
Copyright: 2006 Andreas Herz. All rights reserved.
Created: 5.11.2006 by Andreas Herz (Web: http://www.freegroup.de )
LICENSE: LGPL
**/
Event=function(){
this.type=null;
this.target=null;
this.relatedTarget=null;
this.cancelable=false;
this.timeStamp=null;
this.returnValue=true;
};
Event.prototype.initEvent=function(sType,_3a0c){
this.type=sType;
this.cancelable=_3a0c;
this.timeStamp=(new Date()).getTime();
};
Event.prototype.preventDefault=function(){
if(this.cancelable){
this.returnValue=false;
}
};
Event.fireDOMEvent=function(_3a0d,_3a0e){
if(document.createEvent){
var evt=document.createEvent("Events");
evt.initEvent(_3a0d,true,true);
_3a0e.dispatchEvent(evt);
}else{
if(document.createEventObject){
var evt=document.createEventObject();
_3a0e.fireEvent("on"+_3a0d,evt);
}
}
};
EventTarget=function(){
this.eventhandlers=new Object();
};
EventTarget.prototype.addEventListener=function(sType,_3a11){
if(typeof this.eventhandlers[sType]=="undefined"){
this.eventhandlers[sType]=new Array;
}
this.eventhandlers[sType][this.eventhandlers[sType].length]=_3a11;
};
EventTarget.prototype.dispatchEvent=function(_3a12){
_3a12.target=this;
if(typeof this.eventhandlers[_3a12.type]!="undefined"){
for(var i=0;i<this.eventhandlers[_3a12.type].length;i++){
this.eventhandlers[_3a12.type][i](_3a12);
}
}
return _3a12.returnValue;
};
EventTarget.prototype.removeEventListener=function(sType,_3a15){
if(typeof this.eventhandlers[sType]!="undefined"){
var _3a16=new Array;
for(var i=0;i<this.eventhandlers[sType].length;i++){
if(this.eventhandlers[sType][i]!=_3a15){
_3a16[_3a16.length]=this.eventhandlers[sType][i];
}
}
this.eventhandlers[sType]=_3a16;
}
};
ArrayList=function(){
this.increment=10;
this.size=0;
this.data=new Array(this.increment);
};
ArrayList.EMPTY_LIST=new ArrayList();
ArrayList.prototype.reverse=function(){
var _3dc7=new Array(this.size);
for(var i=0;i<this.size;i++){
_3dc7[i]=this.data[this.size-i-1];
}
this.data=_3dc7;
};
ArrayList.prototype.getCapacity=function(){
return this.data.length;
};
ArrayList.prototype.getSize=function(){
return this.size;
};
ArrayList.prototype.isEmpty=function(){
return this.getSize()==0;
};
ArrayList.prototype.getLastElement=function(){
if(this.data[this.getSize()-1]!=null){
return this.data[this.getSize()-1];
}
};
ArrayList.prototype.getFirstElement=function(){
if(this.data[0]!=null){
return this.data[0];
}
};
ArrayList.prototype.get=function(i){
return this.data[i];
};
ArrayList.prototype.add=function(obj){
if(this.getSize()==this.data.length){
this.resize();
}
this.data[this.size++]=obj;
};
ArrayList.prototype.addAll=function(obj){
for(var i=0;i<obj.getSize();i++){
this.add(obj.get(i));
}
};
ArrayList.prototype.remove=function(obj){
var index=this.indexOf(obj);
if(index>=0){
return this.removeElementAt(index);
}
return null;
};
ArrayList.prototype.insertElementAt=function(obj,index){
if(this.size==this.capacity){
this.resize();
}
for(var i=this.getSize();i>index;i--){
this.data[i]=this.data[i-1];
}
this.data[index]=obj;
this.size++;
};
ArrayList.prototype.removeElementAt=function(index){
var _3dd3=this.data[index];
for(var i=index;i<(this.getSize()-1);i++){
this.data[i]=this.data[i+1];
}
this.data[this.getSize()-1]=null;
this.size--;
return _3dd3;
};
ArrayList.prototype.removeAllElements=function(){
this.size=0;
for(var i=0;i<this.data.length;i++){
this.data[i]=null;
}
};
ArrayList.prototype.indexOf=function(obj){
for(var i=0;i<this.getSize();i++){
if(this.data[i]==obj){
return i;
}
}
return -1;
};
ArrayList.prototype.contains=function(obj){
for(var i=0;i<this.getSize();i++){
if(this.data[i]==obj){
return true;
}
}
return false;
};
ArrayList.prototype.resize=function(){
newData=new Array(this.data.length+this.increment);
for(var i=0;i<this.data.length;i++){
newData[i]=this.data[i];
}
this.data=newData;
};
ArrayList.prototype.trimToSize=function(){
var temp=new Array(this.getSize());
for(var i=0;i<this.getSize();i++){
temp[i]=this.data[i];
}
this.size=temp.length-1;
this.data=temp;
};
ArrayList.prototype.sort=function(f){
var i,j;
var _3ddf;
var _3de0;
var _3de1;
var _3de2;
for(i=1;i<this.getSize();i++){
_3de0=this.data[i];
_3ddf=_3de0[f];
j=i-1;
_3de1=this.data[j];
_3de2=_3de1[f];
while(j>=0&&_3de2>_3ddf){
this.data[j+1]=this.data[j];
j--;
if(j>=0){
_3de1=this.data[j];
_3de2=_3de1[f];
}
}
this.data[j+1]=_3de0;
}
};
ArrayList.prototype.clone=function(){
var _3de3=new ArrayList(this.size);
for(var i=0;i<this.size;i++){
_3de3.add(this.data[i]);
}
return _3de3;
};
ArrayList.prototype.overwriteElementAt=function(obj,index){
this.data[index]=obj;
};
function trace(_3dbe){
var _3dbf=openwindow("about:blank",700,400);
_3dbf.document.writeln("<pre>"+_3dbe+"</pre>");
}
function openwindow(url,width,_3dc2){
var left=(screen.width-width)/2;
var top=(screen.height-_3dc2)/2;
property="left="+left+", top="+top+", toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,alwaysRaised,width="+width+",height="+_3dc2;
return window.open(url,"_blank",property);
}
function dumpObject(obj){
trace("----------------------------------------------------------------------------");
trace("- Object dump");
trace("----------------------------------------------------------------------------");
for(var i in obj){
try{
if(typeof obj[i]!="function"){
trace(i+" --> "+obj[i]);
}
}
catch(e){
}
}
for(var i in obj){
try{
if(typeof obj[i]=="function"){
trace(i+" --> "+obj[i]);
}
}
catch(e){
}
}
trace("----------------------------------------------------------------------------");
}
Drag=function(){
};
Drag.current=null;
Drag.currentTarget=null;
Drag.dragging=false;
Drag.isDragging=function(){
return this.dragging;
};
Drag.setCurrent=function(_326a){
this.current=_326a;
this.dragging=true;
};
Drag.getCurrent=function(){
return this.current;
};
Drag.clearCurrent=function(){
this.current=null;
this.dragging=false;
};
Draggable=function(_326b,_326c){
EventTarget.call(this);
this.construct(_326b,_326c);
this.diffX=0;
this.diffY=0;
this.targets=new ArrayList();
};
Draggable.prototype=new EventTarget;
Draggable.prototype.construct=function(_326d,_326e){
this.element=_326d;
this.constraints=_326e;
var oThis=this;
var _3270=function(){
var _3271=new DragDropEvent();
_3271.initDragDropEvent("dblclick",true);
oThis.dispatchEvent(_3271);
var _3272=arguments[0]||window.event;
_3272.cancelBubble=true;
_3272.returnValue=false;
};
var _3273=function(){
var _3274=arguments[0]||window.event;
var _3275=new DragDropEvent();
var _3276=oThis.node.workflow.getAbsoluteX();
var _3277=oThis.node.workflow.getAbsoluteY();
var _3278=oThis.node.workflow.getScrollLeft();
var _3279=oThis.node.workflow.getScrollTop();
_3275.x=_3274.clientX-oThis.element.offsetLeft+_3278-_3276;
_3275.y=_3274.clientY-oThis.element.offsetTop+_3279-_3277;
if(_3274.button==2){
_3275.initDragDropEvent("contextmenu",true);
oThis.dispatchEvent(_3275);
}else{
_3275.initDragDropEvent("dragstart",true);
if(oThis.dispatchEvent(_3275)){
oThis.diffX=_3274.clientX-oThis.element.offsetLeft;
oThis.diffY=_3274.clientY-oThis.element.offsetTop;
Drag.setCurrent(oThis);
if(oThis.isAttached==true){
oThis.detachEventHandlers();
}
oThis.attachEventHandlers();
}
}
_3274.cancelBubble=true;
_3274.returnValue=false;
};
var _327a=function(){
if(Drag.getCurrent()==null){
var _327b=arguments[0]||window.event;
if(Drag.currentHover!=null&&oThis!=Drag.currentHover){
var _327c=new DragDropEvent();
_327c.initDragDropEvent("mouseleave",false,oThis);
Drag.currentHover.dispatchEvent(_327c);
}
if(oThis!=null&&oThis!=Drag.currentHover){
var _327c=new DragDropEvent();
_327c.initDragDropEvent("mouseenter",false,oThis);
oThis.dispatchEvent(_327c);
}
Drag.currentHover=oThis;
}else{
}
};
if(this.element.addEventListener){
this.element.addEventListener("mousemove",_327a,false);
this.element.addEventListener("mousedown",_3273,false);
this.element.addEventListener("dblclick",_3270,false);
}else{
if(this.element.attachEvent){
this.element.attachEvent("onmousemove",_327a);
this.element.attachEvent("onmousedown",_3273);
this.element.attachEvent("ondblclick",_3270);
}else{
throw new Error("Drag not supported in this browser.");
}
}
};
Draggable.prototype.attachEventHandlers=function(){
var oThis=this;
oThis.isAttached=true;
this.tempMouseMove=function(){
var _327e=arguments[0]||window.event;
var _327f=new Point(_327e.clientX-oThis.diffX,_327e.clientY-oThis.diffY);
if(oThis.node.getCanSnapToHelper()){
_327f=oThis.node.getWorkflow().snapToHelper(oThis.node,_327f);
}
oThis.element.style.left=_327f.x+"px";
oThis.element.style.top=_327f.y+"px";
var _3280=oThis.node.workflow.getScrollLeft();
var _3281=oThis.node.workflow.getScrollTop();
var _3282=oThis.node.workflow.getAbsoluteX();
var _3283=oThis.node.workflow.getAbsoluteY();
var _3284=oThis.getDropTarget(_327e.clientX+_3280-_3282,_327e.clientY+_3281-_3283);
var _3285=oThis.getCompartment(_327e.clientX+_3280-_3282,_327e.clientY+_3281-_3283);
if(Drag.currentTarget!=null&&_3284!=Drag.currentTarget){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("dragleave",false,oThis);
Drag.currentTarget.dispatchEvent(_3286);
}
if(_3284!=null&&_3284!=Drag.currentTarget){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("dragenter",false,oThis);
_3284.dispatchEvent(_3286);
}
Drag.currentTarget=_3284;
if(Drag.currentCompartment!=null&&_3285!=Drag.currentCompartment){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("figureleave",false,oThis);
Drag.currentCompartment.dispatchEvent(_3286);
}
if(_3285!=null&&_3285.node!=oThis.node&&_3285!=Drag.currentCompartment){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("figureenter",false,oThis);
_3285.dispatchEvent(_3286);
}
Drag.currentCompartment=_3285;
var _3287=new DragDropEvent();
_3287.initDragDropEvent("drag",false);
oThis.dispatchEvent(_3287);
};
oThis.tempMouseUp=function(){
oThis.detachEventHandlers();
var _3288=arguments[0]||window.event;
var _3289=new DragDropEvent();
_3289.initDragDropEvent("dragend",false);
oThis.dispatchEvent(_3289);
var _328a=oThis.node.workflow.getScrollLeft();
var _328b=oThis.node.workflow.getScrollTop();
var _328c=oThis.node.workflow.getAbsoluteX();
var _328d=oThis.node.workflow.getAbsoluteY();
var _328e=oThis.getDropTarget(_3288.clientX+_328a-_328c,_3288.clientY+_328b-_328d);
var _328f=oThis.getCompartment(_3288.clientX+_328a-_328c,_3288.clientY+_328b-_328d);
if(_328e!=null){
var _3290=new DragDropEvent();
_3290.initDragDropEvent("drop",false,oThis);
_328e.dispatchEvent(_3290);
}
if(_328f!=null&&_328f.node!=oThis.node){
var _3290=new DragDropEvent();
_3290.initDragDropEvent("figuredrop",false,oThis);
_328f.dispatchEvent(_3290);
}
if(Drag.currentTarget!=null){
var _3290=new DragDropEvent();
_3290.initDragDropEvent("dragleave",false,oThis);
Drag.currentTarget.dispatchEvent(_3290);
Drag.currentTarget=null;
}
Drag.currentCompartment=null;
Drag.clearCurrent();
};
if(document.body.addEventListener){
document.body.addEventListener("mousemove",this.tempMouseMove,false);
document.body.addEventListener("mouseup",this.tempMouseUp,false);
}else{
if(document.body.attachEvent){
document.body.attachEvent("onmousemove",this.tempMouseMove);
document.body.attachEvent("onmouseup",this.tempMouseUp);
}else{
throw new Error("Drag doesn't support this browser.");
}
}
};
Draggable.prototype.detachEventHandlers=function(){
this.isAttached=false;
if(document.body.removeEventListener){
document.body.removeEventListener("mousemove",this.tempMouseMove,false);
document.body.removeEventListener("mouseup",this.tempMouseUp,false);
}else{
if(document.body.detachEvent){
document.body.detachEvent("onmousemove",this.tempMouseMove);
document.body.detachEvent("onmouseup",this.tempMouseUp);
}else{
throw new Error("Drag doesn't support this browser.");
}
}
};
Draggable.prototype.getDropTarget=function(x,y){
for(var i=0;i<this.targets.getSize();i++){
var _3294=this.targets.get(i);
if(_3294.node.isOver(x,y)&&_3294.node!=this.node){
return _3294;
}
}
return null;
};
Draggable.prototype.getCompartment=function(x,y){
var _3297=null;
for(var i=0;i<this.node.workflow.compartments.getSize();i++){
var _3299=this.node.workflow.compartments.get(i);
if(_3299.isOver(x,y)&&_3299!=this.node){
if(_3297==null){
_3297=_3299;
}else{
if(_3297.getZOrder()<_3299.getZOrder()){
_3297=_3299;
}
}
}
}
return _3297==null?null:_3297.dropable;
};
Draggable.prototype.getLeft=function(){
return this.element.offsetLeft;
};
Draggable.prototype.getTop=function(){
return this.element.offsetTop;
};
DragDropEvent=function(){
Event.call(this);
};
DragDropEvent.prototype=new Event();
DragDropEvent.prototype.initDragDropEvent=function(sType,_329b,_329c){
this.initEvent(sType,_329b);
this.relatedTarget=_329c;
};
DropTarget=function(_329d){
EventTarget.call(this);
this.construct(_329d);
};
DropTarget.prototype=new EventTarget;
DropTarget.prototype.construct=function(_329e){
this.element=_329e;
};
DropTarget.prototype.getLeft=function(){
var el=this.element;
var ol=el.offsetLeft;
while((el=el.offsetParent)!=null){
ol+=el.offsetLeft;
}
return ol;
};
DropTarget.prototype.getTop=function(){
var el=this.element;
var ot=el.offsetTop;
while((el=el.offsetParent)!=null){
ot+=el.offsetTop;
}
return ot;
};
DropTarget.prototype.getHeight=function(){
return this.element.offsetHeight;
};
DropTarget.prototype.getWidth=function(){
return this.element.offsetWidth;
};
PositionConstants=function(){
};
PositionConstants.NORTH=1;
PositionConstants.SOUTH=4;
PositionConstants.WEST=8;
PositionConstants.EAST=16;
Color=function(red,green,blue){
if(typeof green=="undefined"){
var rgb=this.hex2rgb(red);
this.red=rgb[0];
this.green=rgb[1];
this.blue=rgb[2];
}else{
this.red=red;
this.green=green;
this.blue=blue;
}
};
Color.prototype.type="Color";
Color.prototype.getHTMLStyle=function(){
return "rgb("+this.red+","+this.green+","+this.blue+")";
};
Color.prototype.getRed=function(){
return this.red;
};
Color.prototype.getGreen=function(){
return this.green;
};
Color.prototype.getBlue=function(){
return this.blue;
};
Color.prototype.getIdealTextColor=function(){
var _3f07=105;
var _3f08=(this.red*0.299)+(this.green*0.587)+(this.blue*0.114);
return (255-_3f08<_3f07)?new Color(0,0,0):new Color(255,255,255);
};
Color.prototype.hex2rgb=function(_3f09){
_3f09=_3f09.replace("#","");
return ({0:parseInt(_3f09.substr(0,2),16),1:parseInt(_3f09.substr(2,2),16),2:parseInt(_3f09.substr(4,2),16)});
};
Color.prototype.hex=function(){
return (this.int2hex(this.red)+this.int2hex(this.green)+this.int2hex(this.blue));
};
Color.prototype.int2hex=function(v){
v=Math.round(Math.min(Math.max(0,v),255));
return ("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16));
};
Color.prototype.darker=function(_3f0b){
var red=parseInt(Math.round(this.getRed()*(1-_3f0b)));
var green=parseInt(Math.round(this.getGreen()*(1-_3f0b)));
var blue=parseInt(Math.round(this.getBlue()*(1-_3f0b)));
if(red<0){
red=0;
}else{
if(red>255){
red=255;
}
}
if(green<0){
green=0;
}else{
if(green>255){
green=255;
}
}
if(blue<0){
blue=0;
}else{
if(blue>255){
blue=255;
}
}
return new Color(red,green,blue);
};
Color.prototype.lighter=function(_3f0f){
var red=parseInt(Math.round(this.getRed()*(1+_3f0f)));
var green=parseInt(Math.round(this.getGreen()*(1+_3f0f)));
var blue=parseInt(Math.round(this.getBlue()*(1+_3f0f)));
if(red<0){
red=0;
}else{
if(red>255){
red=255;
}
}
if(green<0){
green=0;
}else{
if(green>255){
green=255;
}
}
if(blue<0){
blue=0;
}else{
if(blue>255){
blue=255;
}
}
return new Color(red,green,blue);
};
Point=function(x,y){
this.x=x;
this.y=y;
};
Point.prototype.type="Point";
Point.prototype.getX=function(){
return this.x;
};
Point.prototype.getY=function(){
return this.y;
};
Point.prototype.getPosition=function(p){
var dx=p.x-this.x;
var dy=p.y-this.y;
if(Math.abs(dx)>Math.abs(dy)){
if(dx<0){
return PositionConstants.WEST;
}
return PositionConstants.EAST;
}
if(dy<0){
return PositionConstants.NORTH;
}
return PositionConstants.SOUTH;
};
Point.prototype.equals=function(o){
return this.x==o.x&&this.y==o.y;
};
Point.prototype.getDistance=function(other){
return Math.sqrt((this.x-other.x)*(this.x-other.x)+(this.y-other.y)*(this.y-other.y));
};
Point.prototype.getTranslated=function(other){
return new Point(this.x+other.x,this.y+other.y);
};
Dimension=function(x,y,w,h){
Point.call(this,x,y);
this.w=w;
this.h=h;
};
Dimension.prototype=new Point;
Dimension.prototype.type="Dimension";
Dimension.prototype.translate=function(dx,dy){
this.x+=dx;
this.y+=dy;
return this;
};
Dimension.prototype.resize=function(dw,dh){
this.w+=dw;
this.h+=dh;
return this;
};
Dimension.prototype.setBounds=function(rect){
this.x=rect.x;
this.y=rect.y;
this.w=rect.w;
this.h=rect.h;
return this;
};
Dimension.prototype.isEmpty=function(){
return this.w<=0||this.h<=0;
};
Dimension.prototype.getWidth=function(){
return this.w;
};
Dimension.prototype.getHeight=function(){
return this.h;
};
Dimension.prototype.getRight=function(){
return this.x+this.w;
};
Dimension.prototype.getBottom=function(){
return this.y+this.h;
};
Dimension.prototype.getTopLeft=function(){
return new Point(this.x,this.y);
};
Dimension.prototype.getCenter=function(){
return new Point(this.x+this.w/2,this.y+this.h/2);
};
Dimension.prototype.getBottomRight=function(){
return new Point(this.x+this.w,this.y+this.h);
};
Dimension.prototype.equals=function(o){
return this.x==o.x&&this.y==o.y&&this.w==o.w&&this.h==o.h;
};
SnapToHelper=function(_3f1b){
this.workflow=_3f1b;
};
SnapToHelper.NORTH=1;
SnapToHelper.SOUTH=4;
SnapToHelper.WEST=8;
SnapToHelper.EAST=16;
SnapToHelper.NORTH_EAST=SnapToHelper.NORTH|SnapToHelper.EAST;
SnapToHelper.NORTH_WEST=SnapToHelper.NORTH|SnapToHelper.WEST;
SnapToHelper.SOUTH_EAST=SnapToHelper.SOUTH|SnapToHelper.EAST;
SnapToHelper.SOUTH_WEST=SnapToHelper.SOUTH|SnapToHelper.WEST;
SnapToHelper.NORTH_SOUTH=SnapToHelper.NORTH|SnapToHelper.SOUTH;
SnapToHelper.EAST_WEST=SnapToHelper.EAST|SnapToHelper.WEST;
SnapToHelper.NSEW=SnapToHelper.NORTH_SOUTH|SnapToHelper.EAST_WEST;
SnapToHelper.prototype.snapPoint=function(_3f1c,_3f1d,_3f1e){
return _3f1d;
};
SnapToHelper.prototype.snapRectangle=function(_3f1f,_3f20){
return _3f1f;
};
SnapToHelper.prototype.onSetDocumentDirty=function(){
};
SnapToGrid=function(_39d9){
SnapToHelper.call(this,_39d9);
};
SnapToGrid.prototype=new SnapToHelper;
SnapToGrid.prototype.snapPoint=function(_39da,_39db,_39dc){
_39dc.x=this.workflow.gridWidthX*Math.floor(((_39db.x+this.workflow.gridWidthX/2)/this.workflow.gridWidthX));
_39dc.y=this.workflow.gridWidthY*Math.floor(((_39db.y+this.workflow.gridWidthY/2)/this.workflow.gridWidthY));
return 0;
};
SnapToGrid.prototype.snapRectangle=function(_39dd,_39de){
_39de.x=_39dd.x;
_39de.y=_39dd.y;
_39de.w=_39dd.w;
_39de.h=_39dd.h;
return 0;
};
SnapToGeometryEntry=function(type,_39cd){
this.type=type;
this.location=_39cd;
};
SnapToGeometryEntry.prototype.getLocation=function(){
return this.location;
};
SnapToGeometryEntry.prototype.getType=function(){
return this.type;
};
SnapToGeometry=function(_40db){
SnapToHelper.call(this,_40db);
};
SnapToGeometry.prototype=new SnapToHelper;
SnapToGeometry.THRESHOLD=5;
SnapToGeometry.prototype.snapPoint=function(_40dc,_40dd,_40de){
if(this.rows==null||this.cols==null){
this.populateRowsAndCols();
}
if((_40dc&SnapToHelper.EAST)!=0){
var _40df=this.getCorrectionFor(this.cols,_40dd.getX()-1,1);
if(_40df!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.EAST;
_40de.x+=_40df;
}
}
if((_40dc&SnapToHelper.WEST)!=0){
var _40e0=this.getCorrectionFor(this.cols,_40dd.getX(),-1);
if(_40e0!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.WEST;
_40de.x+=_40e0;
}
}
if((_40dc&SnapToHelper.SOUTH)!=0){
var _40e1=this.getCorrectionFor(this.rows,_40dd.getY()-1,1);
if(_40e1!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.SOUTH;
_40de.y+=_40e1;
}
}
if((_40dc&SnapToHelper.NORTH)!=0){
var _40e2=this.getCorrectionFor(this.rows,_40dd.getY(),-1);
if(_40e2!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.NORTH;
_40de.y+=_40e2;
}
}
return _40dc;
};
SnapToGeometry.prototype.snapRectangle=function(_40e3,_40e4){
var _40e5=_40e3.getTopLeft();
var _40e6=_40e3.getBottomRight();
var _40e7=this.snapPoint(SnapToHelper.NORTH_WEST,_40e3.getTopLeft(),_40e5);
_40e4.x=_40e5.x;
_40e4.y=_40e5.y;
var _40e8=this.snapPoint(SnapToHelper.SOUTH_EAST,_40e3.getBottomRight(),_40e6);
if(_40e7&SnapToHelper.WEST){
_40e4.x=_40e6.x-_40e3.getWidth();
}
if(_40e7&SnapToHelper.NORTH){
_40e4.y=_40e6.y-_40e3.getHeight();
}
return _40e7|_40e8;
};
SnapToGeometry.prototype.populateRowsAndCols=function(){
this.rows=new Array();
this.cols=new Array();
var _40e9=this.workflow.getDocument().getFigures();
var index=0;
for(var i=0;i<_40e9.getSize();i++){
var _40ec=_40e9.get(i);
if(_40ec!=this.workflow.getCurrentSelection()){
var _40ed=_40ec.getBounds();
this.cols[index*3]=new SnapToGeometryEntry(-1,_40ed.getX());
this.rows[index*3]=new SnapToGeometryEntry(-1,_40ed.getY());
this.cols[index*3+1]=new SnapToGeometryEntry(0,_40ed.x+(_40ed.getWidth()-1)/2);
this.rows[index*3+1]=new SnapToGeometryEntry(0,_40ed.y+(_40ed.getHeight()-1)/2);
this.cols[index*3+2]=new SnapToGeometryEntry(1,_40ed.getRight()-1);
this.rows[index*3+2]=new SnapToGeometryEntry(1,_40ed.getBottom()-1);
index++;
}
}
};
SnapToGeometry.prototype.getCorrectionFor=function(_40ee,value,side){
var _40f1=SnapToGeometry.THRESHOLD;
var _40f2=SnapToGeometry.THRESHOLD;
for(var i=0;i<_40ee.length;i++){
var entry=_40ee[i];
var _40f5;
if(entry.type==-1&&side!=0){
_40f5=Math.abs(value-entry.location);
if(_40f5<_40f1){
_40f1=_40f5;
_40f2=entry.location-value;
}
}else{
if(entry.type==0&&side==0){
_40f5=Math.abs(value-entry.location);
if(_40f5<_40f1){
_40f1=_40f5;
_40f2=entry.location-value;
}
}else{
if(entry.type==1&&side!=0){
_40f5=Math.abs(value-entry.location);
if(_40f5<_40f1){
_40f1=_40f5;
_40f2=entry.location-value;
}
}
}
}
}
return _40f2;
};
SnapToGeometry.prototype.onSetDocumentDirty=function(){
this.rows=null;
this.cols=null;
};
Border=function(){
this.color=null;
};
Border.prototype.type="Border";
Border.prototype.dispose=function(){
this.color=null;
};
Border.prototype.getHTMLStyle=function(){
return "";
};
Border.prototype.setColor=function(c){
this.color=c;
};
Border.prototype.getColor=function(){
return this.color;
};
Border.prototype.refresh=function(){
};
LineBorder=function(width){
Border.call(this);
this.width=1;
if(width){
this.width=width;
}
this.figure=null;
};
LineBorder.prototype=new Border;
LineBorder.prototype.type="LineBorder";
LineBorder.prototype.dispose=function(){
Border.prototype.dispose.call(this);
this.figure=null;
};
LineBorder.prototype.setLineWidth=function(w){
this.width=w;
if(this.figure!=null){
this.figure.html.style.border=this.getHTMLStyle();
}
};
LineBorder.prototype.getHTMLStyle=function(){
if(this.getColor()!=null){
return this.width+"px solid "+this.getColor().getHTMLStyle();
}
return this.width+"px solid black";
};
LineBorder.prototype.refresh=function(){
this.setLineWidth(this.width);
};
Figure=function(){
this.construct();
};
Figure.prototype.type="Figure";
Figure.ZOrderBaseIndex=100;
Figure.setZOrderBaseIndex=function(index){
Figure.ZOrderBaseIndex=index;
};
Figure.prototype.construct=function(){
this.lastDragStartTime=0;
this.x=0;
this.y=0;
this.border=null;
this.setDimension(10,10);
this.id=this.generateUId();
this.html=this.createHTMLElement();
this.canvas=null;
this.workflow=null;
this.draggable=null;
this.parent=null;
this.isMoving=false;
this.canSnapToHelper=true;
this.snapToGridAnchor=new Point(0,0);
this.timer=-1;
this.setDeleteable(true);
this.setCanDrag(true);
this.setResizeable(true);
this.setSelectable(true);
this.properties=new Object();
this.moveListener=new ArrayList();
};
Figure.prototype.dispose=function(){
this.canvas=null;
this.workflow=null;
this.moveListener=null;
if(this.draggable!=null){
this.draggable.removeEventListener("mouseenter",this.tmpMouseEnter);
this.draggable.removeEventListener("mouseleave",this.tmpMouseLeave);
this.draggable.removeEventListener("dragend",this.tmpDragend);
this.draggable.removeEventListener("dragstart",this.tmpDragstart);
this.draggable.removeEventListener("drag",this.tmpDrag);
this.draggable.removeEventListener("dblclick",this.tmpDoubleClick);
this.draggable.node=null;
}
this.draggable=null;
if(this.border!=null){
this.border.dispose();
}
this.border=null;
if(this.parent!=null){
this.parent.removeChild(this);
}
};
Figure.prototype.getProperties=function(){
return this.properties;
};
Figure.prototype.getProperty=function(key){
return this.properties[key];
};
Figure.prototype.setProperty=function(key,value){
this.properties[key]=value;
this.setDocumentDirty();
};
Figure.prototype.getId=function(){
return this.id;
};
Figure.prototype.setCanvas=function(_3deb){
this.canvas=_3deb;
};
Figure.prototype.getWorkflow=function(){
return this.workflow;
};
Figure.prototype.setWorkflow=function(_3dec){
if(this.draggable==null){
this.html.tabIndex="0";
var oThis=this;
this.keyDown=function(event){
event.cancelBubble=true;
event.returnValue=true;
oThis.onKeyDown(event.keyCode,event.ctrlKey);
};
if(this.html.addEventListener){
this.html.addEventListener("keydown",this.keyDown,false);
}else{
if(this.html.attachEvent){
this.html.attachEvent("onkeydown",this.keyDown);
}
}
this.draggable=new Draggable(this.html,Draggable.DRAG_X|Draggable.DRAG_Y);
this.draggable.node=this;
this.tmpContextMenu=function(_3def){
oThis.onContextMenu(oThis.x+_3def.x,_3def.y+oThis.y);
};
this.tmpMouseEnter=function(_3df0){
oThis.onMouseEnter();
};
this.tmpMouseLeave=function(_3df1){
oThis.onMouseLeave();
};
this.tmpDragend=function(_3df2){
oThis.onDragend();
};
this.tmpDragstart=function(_3df3){
var w=oThis.workflow;
w.showMenu(null);
if(oThis.workflow.toolPalette&&oThis.workflow.toolPalette.activeTool){
_3df3.returnValue=false;
oThis.workflow.onMouseDown(oThis.x+_3df3.x,_3df3.y+oThis.y);
oThis.workflow.onMouseUp(oThis.x+_3df3.x,_3df3.y+oThis.y);
return;
}
_3df3.returnValue=oThis.onDragstart(_3df3.x,_3df3.y);
};
this.tmpDrag=function(_3df5){
oThis.onDrag();
};
this.tmpDoubleClick=function(_3df6){
oThis.onDoubleClick();
};
this.draggable.addEventListener("contextmenu",this.tmpContextMenu);
this.draggable.addEventListener("mouseenter",this.tmpMouseEnter);
this.draggable.addEventListener("mouseleave",this.tmpMouseLeave);
this.draggable.addEventListener("dragend",this.tmpDragend);
this.draggable.addEventListener("dragstart",this.tmpDragstart);
this.draggable.addEventListener("drag",this.tmpDrag);
this.draggable.addEventListener("dblclick",this.tmpDoubleClick);
}
this.workflow=_3dec;
};
Figure.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height=this.width+"px";
item.style.width=this.height+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.outline="none";
item.style.zIndex=""+Figure.ZOrderBaseIndex;
return item;
};
Figure.prototype.setParent=function(_3df8){
this.parent=_3df8;
};
Figure.prototype.getParent=function(){
return this.parent;
};
Figure.prototype.getZOrder=function(){
return this.html.style.zIndex;
};
Figure.prototype.setZOrder=function(index){
this.html.style.zIndex=index;
};
Figure.prototype.hasFixedPosition=function(){
return false;
};
Figure.prototype.getMinWidth=function(){
return 5;
};
Figure.prototype.getMinHeight=function(){
return 5;
};
Figure.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
Figure.prototype.paint=function(){
};
Figure.prototype.setBorder=function(_3dfa){
if(this.border!=null){
this.border.figure=null;
}
this.border=_3dfa;
this.border.figure=this;
this.border.refresh();
this.setDocumentDirty();
};
Figure.prototype.onContextMenu=function(x,y){
var menu=this.getContextMenu();
if(menu!=null){
this.workflow.showMenu(menu,x,y);
}
};
Figure.prototype.getContextMenu=function(){
return null;
};
Figure.prototype.onDoubleClick=function(){
};
Figure.prototype.onMouseEnter=function(){
};
Figure.prototype.onMouseLeave=function(){
};
Figure.prototype.onDrag=function(){
this.x=this.draggable.getLeft();
this.y=this.draggable.getTop();
if(this.isMoving==false){
this.isMoving=true;
this.setAlpha(0.5);
}
this.fireMoveEvent();
};
Figure.prototype.onDragend=function(){
if(this.getWorkflow().getEnableSmoothFigureHandling()==true){
var _3dfe=this;
var _3dff=function(){
if(_3dfe.alpha<1){
_3dfe.setAlpha(Math.min(1,_3dfe.alpha+0.05));
}else{
window.clearInterval(_3dfe.timer);
_3dfe.timer=-1;
}
};
if(_3dfe.timer>0){
window.clearInterval(_3dfe.timer);
}
_3dfe.timer=window.setInterval(_3dff,20);
}else{
this.setAlpha(1);
}
this.command.setPosition(this.x,this.y);
this.workflow.commandStack.execute(this.command);
this.command=null;
this.isMoving=false;
this.workflow.hideSnapToHelperLines();
this.fireMoveEvent();
};
Figure.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
this.command=new CommandMove(this,this.x,this.y);
return true;
};
Figure.prototype.setCanDrag=function(flag){
this.canDrag=flag;
if(flag){
this.html.style.cursor="move";
}else{
this.html.style.cursor=null;
}
};
Figure.prototype.setAlpha=function(_3e03){
if(this.alpha==_3e03){
return;
}
try{
this.html.style.MozOpacity=_3e03;
}
catch(exc){
}
try{
this.html.style.opacity=_3e03;
}
catch(exc){
}
try{
var _3e04=Math.round(_3e03*100);
if(_3e04>=99){
this.html.style.filter="";
}else{
this.html.style.filter="alpha(opacity="+_3e04+")";
}
}
catch(exc){
}
this.alpha=_3e03;
};
Figure.prototype.setDimension=function(w,h){
this.width=Math.max(this.getMinWidth(),w);
this.height=Math.max(this.getMinHeight(),h);
if(this.html==null){
return;
}
this.html.style.width=this.width+"px";
this.html.style.height=this.height+"px";
this.fireMoveEvent();
if(this.workflow!=null&&this.workflow.getCurrentSelection()==this){
this.workflow.showResizeHandles(this);
}
};
Figure.prototype.setPosition=function(xPos,yPos){
this.x=xPos;
this.y=yPos;
if(this.html==null){
return;
}
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
this.fireMoveEvent();
if(this.workflow!=null&&this.workflow.getCurrentSelection()==this){
this.workflow.showResizeHandles(this);
}
};
Figure.prototype.isResizeable=function(){
return this.resizeable;
};
Figure.prototype.setResizeable=function(flag){
this.resizeable=flag;
};
Figure.prototype.isSelectable=function(){
return this.selectable;
};
Figure.prototype.setSelectable=function(flag){
this.selectable=flag;
};
Figure.prototype.isStrechable=function(){
return true;
};
Figure.prototype.isDeleteable=function(){
return this.deleteable;
};
Figure.prototype.setDeleteable=function(flag){
this.deleteable=flag;
};
Figure.prototype.setCanSnapToHelper=function(flag){
this.canSnapToHelper=flag;
};
Figure.prototype.getCanSnapToHelper=function(){
return this.canSnapToHelper;
};
Figure.prototype.getSnapToGridAnchor=function(){
return this.snapToGridAnchor;
};
Figure.prototype.setSnapToGridAnchor=function(point){
this.snapToGridAnchor=point;
};
Figure.prototype.getBounds=function(){
return new Dimension(this.getX(),this.getY(),this.getWidth(),this.getHeight());
};
Figure.prototype.getWidth=function(){
return this.width;
};
Figure.prototype.getHeight=function(){
return this.height;
};
Figure.prototype.getY=function(){
return this.y;
};
Figure.prototype.getX=function(){
return this.x;
};
Figure.prototype.getAbsoluteY=function(){
return this.y;
};
Figure.prototype.getAbsoluteX=function(){
return this.x;
};
Figure.prototype.onKeyDown=function(_3e0e,ctrl){
if(_3e0e==46&&this.isDeleteable()==true){
this.workflow.commandStack.execute(new CommandDelete(this));
}
if(ctrl){
this.workflow.onKeyDown(_3e0e,ctrl);
}
};
Figure.prototype.getPosition=function(){
return new Point(this.x,this.y);
};
Figure.prototype.isOver=function(iX,iY){
var x=this.getAbsoluteX();
var y=this.getAbsoluteY();
var iX2=x+this.width;
var iY2=y+this.height;
return (iX>=x&&iX<=iX2&&iY>=y&&iY<=iY2);
};
Figure.prototype.attachMoveListener=function(_3e16){
if(_3e16==null||this.moveListener==null){
return;
}
this.moveListener.add(_3e16);
};
Figure.prototype.detachMoveListener=function(_3e17){
if(_3e17==null||this.moveListener==null){
return;
}
this.moveListener.remove(_3e17);
};
Figure.prototype.fireMoveEvent=function(){
this.setDocumentDirty();
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
this.moveListener.get(i).onOtherFigureMoved(this);
}
};
Figure.prototype.onOtherFigureMoved=function(_3e1a){
};
Figure.prototype.setDocumentDirty=function(){
if(this.workflow!=null){
this.workflow.setDocumentDirty();
}
};
Figure.prototype.generateUId=function(){
var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var _3e1c=10;
var _3e1d=10;
nbTry=0;
while(nbTry<1000){
var id="";
for(var i=0;i<_3e1c;i++){
var rnum=Math.floor(Math.random()*chars.length);
id+=chars.substring(rnum,rnum+1);
}
elem=document.getElementById(id);
if(!elem){
return id;
}
nbTry+=1;
}
return null;
};
Figure.prototype.disableTextSelection=function(e){
if(typeof e.onselectstart!="undefined"){
e.onselectstart=function(){
return false;
};
}else{
if(typeof e.style.MozUserSelect!="undefined"){
e.style.MozUserSelect="none";
}
}
};
Node=function(){
this.bgColor=null;
this.lineColor=new Color(128,128,255);
this.lineStroke=1;
this.ports=new ArrayList();
Figure.call(this);
};
Node.prototype=new Figure;
Node.prototype.type="Node";
Node.prototype.dispose=function(){
for(var i=0;i<this.ports.getSize();i++){
this.ports.get(i).dispose();
}
this.ports=null;
Figure.prototype.dispose.call(this);
};
Node.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.width="auto";
item.style.height="auto";
item.style.margin="0px";
item.style.padding="0px";
if(this.lineColor!=null){
item.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}
item.style.fontSize="1px";
if(this.bgColor!=null){
item.style.backgroundColor=this.bgColor.getHTMLStyle();
}
return item;
};
Node.prototype.paint=function(){
Figure.prototype.paint.call(this);
for(var i=0;i<this.ports.getSize();i++){
this.ports.get(i).paint();
}
};
Node.prototype.getPorts=function(){
return this.ports;
};
Node.prototype.getPort=function(_32a7){
if(this.ports==null){
return null;
}
for(var i=0;i<this.ports.getSize();i++){
var port=this.ports.get(i);
if(port.getName()==_32a7){
return port;
}
}
};
Node.prototype.addPort=function(port,x,y){
this.ports.add(port);
port.setOrigin(x,y);
port.setPosition(x,y);
port.setParent(this);
port.setDeleteable(false);
this.html.appendChild(port.getHTMLElement());
if(this.workflow!=null){
this.workflow.registerPort(port);
}
};
Node.prototype.removePort=function(port){
if(this.ports!=null){
this.ports.removeElementAt(this.ports.indexOf(port));
}
try{
this.html.removeChild(port.getHTMLElement());
}
catch(exc){
}
if(this.workflow!=null){
this.workflow.unregisterPort(port);
}
};
Node.prototype.setWorkflow=function(_32ae){
var _32af=this.workflow;
Figure.prototype.setWorkflow.call(this,_32ae);
if(_32af!=null){
for(var i=0;i<this.ports.getSize();i++){
_32af.unregisterPort(this.ports.get(i));
}
}
if(this.workflow!=null){
for(var i=0;i<this.ports.getSize();i++){
this.workflow.registerPort(this.ports.get(i));
}
}
};
Node.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Node.prototype.getBackgroundColor=function(){
return this.bgColor;
};
Node.prototype.setColor=function(color){
this.lineColor=color;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border="0px";
}
};
Node.prototype.setLineWidth=function(w){
this.lineStroke=w;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border="0px";
}
};
VectorFigure=function(){
this.bgColor=null;
this.lineColor=new Color(0,0,0);
this.stroke=1;
this.graphics=null;
Node.call(this);
};
VectorFigure.prototype=new Node;
VectorFigure.prototype.type="VectorFigure";
VectorFigure.prototype.dispose=function(){
Node.prototype.dispose.call(this);
this.bgColor=null;
this.lineColor=null;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
VectorFigure.prototype.createHTMLElement=function(){
var item=Node.prototype.createHTMLElement.call(this);
item.style.border="0px";
item.style.backgroundColor="transparent";
return item;
};
VectorFigure.prototype.setWorkflow=function(_3e71){
Node.prototype.setWorkflow.call(this,_3e71);
if(this.workflow==null){
this.graphics.clear();
this.graphics=null;
}
};
VectorFigure.prototype.paint=function(){
if(this.graphics==null){
this.graphics=new jsGraphics(this.id);
}else{
this.graphics.clear();
}
Node.prototype.paint.call(this);
for(var i=0;i<this.ports.getSize();i++){
this.getHTMLElement().appendChild(this.ports.get(i).getHTMLElement());
}
};
VectorFigure.prototype.setDimension=function(w,h){
Node.prototype.setDimension.call(this,w,h);
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.setTaskCount=function(_40c0){
}
VectorFigure.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.getBackgroundColor=function(){
return this.bgColor;
};
VectorFigure.prototype.setLineWidth=function(w){
this.stroke=w;
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.setColor=function(color){
this.lineColor=color;
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.getColor=function(){
return this.lineColor;
};
SVGFigure=function(width,_30b2){
this.bgColor=null;
this.lineColor=new Color(0,0,0);
this.stroke=1;
this.context=null;
Node.call(this);
if(width&&_30b2){
this.setDimension(width,_30b2);
}
};
SVGFigure.prototype=new Node;
SVGFigure.prototype.type="SVGFigure";
SVGFigure.prototype.createHTMLElement=function(){
var item=new MooCanvas(this.id,{width:this.getWidth(),height:this.getHeight()});
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.zIndex=""+Figure.ZOrderBaseIndex;
this.context=item.getContext("2d");
return item;
};
SVGFigure.prototype.paint=function(){
this.context.clearRect(0,0,this.getWidth(),this.getHeight());
this.context.fillStyle="rgba(200,0,0,0.3)";
this.context.fillRect(0,0,this.getWidth(),this.getHeight());
};
SVGFigure.prototype.setDimension=function(w,h){
Node.prototype.setDimension.call(this,w,h);
this.html.width=w;
this.html.height=h;
if(this.context!=null){
this.paint();
}
};
SVGFigure.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.graphics!=null){
this.paint();
}
};
SVGFigure.prototype.getBackgroundColor=function(){
return this.bgColor;
};
SVGFigure.prototype.setLineWidth=function(w){
this.stroke=w;
if(this.context!=null){
this.paint();
}
};
SVGFigure.prototype.setColor=function(color){
this.lineColor=color;
if(this.context!=null){
this.paint();
}
};
SVGFigure.prototype.getColor=function(){
return this.lineColor;
};
Label=function(msg){
this.msg=msg;
this.bgColor=null;
this.color=new Color(0,0,0);
this.fontSize=10;
this.textNode=null;
this.align="center";
Figure.call(this);
};
Label.prototype=new Figure;
Label.prototype.type="Label";
Label.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
this.textNode=document.createTextNode(this.msg);
item.appendChild(this.textNode);
item.style.color=this.color.getHTMLStyle();
item.style.fontSize=this.fontSize+"pt";
item.style.width="auto";
item.style.height="auto";
item.style.paddingLeft="3px";
item.style.paddingRight="3px";
item.style.textAlign=this.align;
if(this.bgColor!=null){
item.style.backgroundColor=this.bgColor.getHTMLStyle();
}
return item;
};
Label.prototype.isResizeable=function(){
return false;
};
Label.prototype.setWordwrap=function(flag){
this.html.style.whiteSpace=flag?"wrap":"nowrap";
};
Label.prototype.setAlign=function(align){
this.align=align;
this.html.style.textAlign=align;
};
Label.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Label.prototype.setColor=function(color){
this.color=color;
this.html.style.color=this.color.getHTMLStyle();
};
Label.prototype.setFontSize=function(size){
this.fontSize=size;
this.html.style.fontSize=this.fontSize+"pt";
};
Label.prototype.getWidth=function(){
if(window.getComputedStyle){
return parseInt(getComputedStyle(this.html,"").getPropertyValue("width"));
}
return parseInt(this.html.clientWidth);
};
Label.prototype.getHeight=function(){
if(window.getComputedStyle){
return parseInt(getComputedStyle(this.html,"").getPropertyValue("height"));
}
return parseInt(this.html.clientHeight);
};
Label.prototype.getText=function(){
this.msg=text;
};
Label.prototype.setText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createTextNode(this.msg);
this.html.appendChild(this.textNode);
};
Label.prototype.setStyledText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createElement("div");
this.textNode.style.whiteSpace="nowrap";
this.textNode.innerHTML=text;
this.html.appendChild(this.textNode);
};
Oval=function(){
VectorFigure.call(this);
};
Oval.prototype=new VectorFigure;
Oval.prototype.type="Oval";
Oval.prototype.paint=function(){
VectorFigure.prototype.paint.call(this);
this.graphics.setStroke(this.stroke);
if(this.bgColor!=null){
this.graphics.setColor(this.bgColor.getHTMLStyle());
this.graphics.fillOval(0,0,this.getWidth()+2,this.getHeight()+2);
}
if(this.lineColor!=null){
this.graphics.setColor(this.lineColor.getHTMLStyle());
this.graphics.drawOval(0,0,this.getWidth()+2,this.getHeight()+2);
}
this.graphics.paint();
};
Circle=function(_3f5f){
Oval.call(this);
if(_3f5f){
this.setDimension(_3f5f,_3f5f);
}
};
Circle.prototype=new Oval;
Circle.prototype.type="Circle";
Circle.prototype.setDimension=function(w,h){
if(w>h){
Oval.prototype.setDimension.call(this,w,w);
}else{
Oval.prototype.setDimension.call(this,h,h);
}
};
Circle.prototype.isStrechable=function(){
return false;
};
Rectangle=function(width,_3e35){
this.bgColor=null;
this.lineColor=new Color(0,0,0);
this.lineStroke=1;
Figure.call(this);
if(width&&_3e35){
this.setDimension(width,_3e35);
}
};
Rectangle.prototype=new Figure;
Rectangle.prototype.type="Rectangle";
Rectangle.prototype.dispose=function(){
Figure.prototype.dispose.call(this);
this.bgColor=null;
this.lineColor=null;
};
Rectangle.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.width="auto";
item.style.height="auto";
item.style.margin="0px";
item.style.padding="0px";
item.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
item.style.fontSize="1px";
item.style.lineHeight="1px";
item.innerHTML=" ";
if(this.bgColor!=null){
item.style.backgroundColor=this.bgColor.getHTMLStyle();
}
return item;
};
Rectangle.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Rectangle.prototype.getBackgroundColor=function(){
return this.bgColor;
};
Rectangle.prototype.setColor=function(color){
this.lineColor=color;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border=this.lineStroke+"0px";
}
};
Rectangle.prototype.getColor=function(){
return this.lineColor;
};
Rectangle.prototype.getWidth=function(){
return Figure.prototype.getWidth.call(this)+2*this.lineStroke;
};
Rectangle.prototype.getHeight=function(){
return Figure.prototype.getHeight.call(this)+2*this.lineStroke;
};
Rectangle.prototype.setDimension=function(w,h){
return Figure.prototype.setDimension.call(this,w-2*this.lineStroke,h-2*this.lineStroke);
};
Rectangle.prototype.setLineWidth=function(w){
var diff=w-this.lineStroke;
this.setDimension(this.getWidth()-2*diff,this.getHeight()-2*diff);
this.lineStroke=w;
var c="transparent";
if(this.lineColor!=null){
c=this.lineColor.getHTMLStyle();
}
this.html.style.border=this.lineStroke+"px solid "+c;
};
Rectangle.prototype.getLineWidth=function(){
return this.lineStroke;
};
ImageFigure=function(url){
this.url=url;
Node.call(this);
this.setDimension(40,40);
};
ImageFigure.prototype=new Node;
ImageFigure.prototype.type="Image";
ImageFigure.prototype.createHTMLElement=function(){
var item=Node.prototype.createHTMLElement.call(this);
item.style.width=this.width+"px";
item.style.height=this.height+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.border="0px";
if(this.url!=null){
item.style.backgroundImage="url("+this.url+")";
}else{
item.style.backgroundImage="";
}
return item;
};
ImageFigure.prototype.setColor=function(color){
};
ImageFigure.prototype.isResizeable=function(){
return false;
};
ImageFigure.prototype.setImage=function(url){
this.url=url;
if(this.url!=null){
this.html.style.backgroundImage="url("+this.url+")";
}else{
this.html.style.backgroundImage="";
}
};
Port=function(_41c2,_41c3){
Corona=function(){
};
Corona.prototype=new Circle;
Corona.prototype.setAlpha=function(_41c4){
Circle.prototype.setAlpha.call(this,Math.min(0.3,_41c4));
};
if(_41c2==null){
this.currentUIRepresentation=new Circle();
}else{
this.currentUIRepresentation=_41c2;
}
if(_41c3==null){
this.connectedUIRepresentation=new Circle();
this.connectedUIRepresentation.setColor(null);
}else{
this.connectedUIRepresentation=_41c3;
}
this.disconnectedUIRepresentation=this.currentUIRepresentation;
this.hideIfConnected=false;
this.uiRepresentationAdded=true;
this.parentNode=null;
this.originX=0;
this.originY=0;
this.coronaWidth=10;
this.corona=null;
Rectangle.call(this);
this.setDimension(8,8);
this.setBackgroundColor(new Color(100,180,100));
this.setColor(new Color(90,150,90));
Rectangle.prototype.setColor.call(this,null);
this.dropable=new DropTarget(this.html);
this.dropable.node=this;
this.dropable.addEventListener("dragenter",function(_41c5){
_41c5.target.node.onDragEnter(_41c5.relatedTarget.node);
});
this.dropable.addEventListener("dragleave",function(_41c6){
_41c6.target.node.onDragLeave(_41c6.relatedTarget.node);
});
this.dropable.addEventListener("drop",function(_41c7){
_41c7.relatedTarget.node.onDrop(_41c7.target.node);
});
};
Port.prototype=new Rectangle;
Port.prototype.type="Port";
Port.ZOrderBaseIndex=5000;
Port.setZOrderBaseIndex=function(index){
Port.ZOrderBaseIndex=index;
};
Port.prototype.setHideIfConnected=function(flag){
this.hideIfConnected=flag;
};
Port.prototype.dispose=function(){
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
var _41cc=this.moveListener.get(i);
this.parentNode.workflow.removeFigure(_41cc);
_41cc.dispose();
}
Rectangle.prototype.dispose.call(this);
this.parentNode=null;
this.dropable.node=null;
this.dropable=null;
this.disconnectedUIRepresentation.dispose();
this.connectedUIRepresentation.dispose();
};
Port.prototype.createHTMLElement=function(){
var item=Rectangle.prototype.createHTMLElement.call(this);
item.style.zIndex=Port.ZOrderBaseIndex;
this.currentUIRepresentation.html.zIndex=Port.ZOrderBaseIndex;
item.appendChild(this.currentUIRepresentation.html);
this.uiRepresentationAdded=true;
return item;
};
Port.prototype.setUiRepresentation=function(_41ce){
if(_41ce==null){
_41ce=new Figure();
}
if(this.uiRepresentationAdded){
//Commented for IE* errors while changing the shape from context menu
//this.html.removeChild(this.currentUIRepresentation.getHTMLElement());
}
this.html.appendChild(_41ce.getHTMLElement());
_41ce.paint();
this.currentUIRepresentation=_41ce;
};
Port.prototype.onMouseEnter=function(){
this.setLineWidth(2);
};
Port.prototype.onMouseLeave=function(){
this.setLineWidth(0);
};
Port.prototype.setDimension=function(width,_41d0){
Rectangle.prototype.setDimension.call(this,width,_41d0);
this.connectedUIRepresentation.setDimension(width,_41d0);
this.disconnectedUIRepresentation.setDimension(width,_41d0);
this.setPosition(this.x,this.y);
};
Port.prototype.setBackgroundColor=function(color){
this.currentUIRepresentation.setBackgroundColor(color);
};
Port.prototype.getBackgroundColor=function(){
return this.currentUIRepresentation.getBackgroundColor();
};
Port.prototype.getConnections=function(){
var _41d2=new ArrayList();
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
var _41d5=this.moveListener.get(i);
if(_41d5 instanceof Connection){
_41d2.add(_41d5);
}
}
return _41d2;
};
Port.prototype.setColor=function(color){
this.currentUIRepresentation.setColor(color);
};
Port.prototype.getColor=function(){
return this.currentUIRepresentation.getColor();
};
Port.prototype.setLineWidth=function(width){
this.currentUIRepresentation.setLineWidth(width);
};
Port.prototype.getLineWidth=function(){
return this.currentUIRepresentation.getLineWidth();
};
Port.prototype.paint=function(){
this.currentUIRepresentation.paint();
};
Port.prototype.setPosition=function(xPos,yPos){
this.originX=xPos;
this.originY=yPos;
Rectangle.prototype.setPosition.call(this,xPos,yPos);
if(this.html==null){
return;
}
this.html.style.left=(this.x-this.getWidth()/2)+"px";
this.html.style.top=(this.y-this.getHeight()/2)+"px";
};
Port.prototype.setParent=function(_41da){
if(this.parentNode!=null){
this.parentNode.detachMoveListener(this);
}
this.parentNode=_41da;
if(this.parentNode!=null){
this.parentNode.attachMoveListener(this);
}
};
Port.prototype.attachMoveListener=function(_41db){
Rectangle.prototype.attachMoveListener.call(this,_41db);
if(this.hideIfConnected==true){
this.setUiRepresentation(this.connectedUIRepresentation);
}
};
Port.prototype.detachMoveListener=function(_41dc){
Rectangle.prototype.detachMoveListener.call(this,_41dc);
if(this.getConnections().getSize()==0){
this.setUiRepresentation(this.disconnectedUIRepresentation);
}
};
Port.prototype.getParent=function(){
return this.parentNode;
};
Port.prototype.onDrag=function(){
Rectangle.prototype.onDrag.call(this);
this.parentNode.workflow.showConnectionLine(this.parentNode.x+this.x,this.parentNode.y+this.y,this.parentNode.x+this.originX,this.parentNode.y+this.originY);
};
Port.prototype.getCoronaWidth=function(){
return this.coronaWidth;
};
Port.prototype.setCoronaWidth=function(width){
this.coronaWidth=width;
};
Port.prototype.onDragend=function(){
this.setAlpha(1);
this.setPosition(this.originX,this.originY);
this.parentNode.workflow.hideConnectionLine();
};
Port.prototype.setOrigin=function(x,y){
this.originX=x;
this.originY=y;
};
Port.prototype.onDragEnter=function(port){
this.parentNode.workflow.connectionLine.setColor(new Color(0,150,0));
this.parentNode.workflow.connectionLine.setLineWidth(3);
this.showCorona(true);
};
Port.prototype.onDragLeave=function(port){
this.parentNode.workflow.connectionLine.setColor(new Color(0,0,0));
this.parentNode.workflow.connectionLine.setLineWidth(1);
this.showCorona(false);
};
Port.prototype.onDrop=function(port){
if(this.parentNode.id==port.parentNode.id){
}else{
var _41e3=new CommandConnect(this.parentNode.workflow,port,this);
this.parentNode.workflow.getCommandStack().execute(_41e3);
}
};
Port.prototype.getAbsolutePosition=function(){
return new Point(this.getAbsoluteX(),this.getAbsoluteY());
};
Port.prototype.getAbsoluteBounds=function(){
return new Dimension(this.getAbsoluteX(),this.getAbsoluteY(),this.getWidth(),this.getHeight());
};
Port.prototype.getAbsoluteY=function(){
return this.originY+this.parentNode.getY();
};
Port.prototype.getAbsoluteX=function(){
return this.originX+this.parentNode.getX();
};
Port.prototype.onOtherFigureMoved=function(_41e4){
this.fireMoveEvent();
};
Port.prototype.getName=function(){
return this.getProperty("name");
};
Port.prototype.setName=function(name){
this.setProperty("name",name);
};
Port.prototype.isOver=function(iX,iY){
var x=this.getAbsoluteX()-this.coronaWidth-this.getWidth()/2;
var y=this.getAbsoluteY()-this.coronaWidth-this.getHeight()/2;
var iX2=x+this.width+(this.coronaWidth*2)+this.getWidth()/2;
var iY2=y+this.height+(this.coronaWidth*2)+this.getHeight()/2;
return (iX>=x&&iX<=iX2&&iY>=y&&iY<=iY2);
};
Port.prototype.showCorona=function(flag,_41ed){
if(flag==true){
this.corona=new Corona();
this.corona.setAlpha(0.3);
this.corona.setBackgroundColor(new Color(0,125,125));
this.corona.setColor(null);
this.corona.setDimension(this.getWidth()+(this.getCoronaWidth()*2),this.getWidth()+(this.getCoronaWidth()*2));
this.parentNode.getWorkflow().addFigure(this.corona,this.getAbsoluteX()-this.getCoronaWidth()-this.getWidth()/2,this.getAbsoluteY()-this.getCoronaWidth()-this.getHeight()/2);
}else{
if(flag==false&&this.corona!=null){
this.parentNode.getWorkflow().removeFigure(this.corona);
this.corona=null;
}
}
};
InputPort=function(_4067){
Port.call(this,_4067);
};
InputPort.prototype=new Port;
InputPort.prototype.type="InputPort";
InputPort.prototype.onDrop=function(port){
if(port.getMaxFanOut&&port.getMaxFanOut()<=port.getFanOut()){
return;
}
if(this.parentNode.id==port.parentNode.id){
}else{
if(port instanceof OutputPort){
var _4069=new CommandConnect(this.parentNode.workflow,port,this);
this.parentNode.workflow.getCommandStack().execute(_4069);
}
}
};
InputPort.prototype.onDragEnter=function(port){
if(port instanceof OutputPort){
Port.prototype.onDragEnter.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof InputPort){
Port.prototype.onDragEnter.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof InputPort){
Port.prototype.onDragEnter.call(this,line.getTarget());
}
}
}
}
};
InputPort.prototype.onDragLeave=function(port){
if(port instanceof OutputPort){
Port.prototype.onDragLeave.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof InputPort){
Port.prototype.onDragLeave.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof InputPort){
Port.prototype.onDragLeave.call(this,line.getTarget());
}
}
}
}
};
OutputPort=function(_357f){
Port.call(this,_357f);
this.maxFanOut=100;
};
OutputPort.prototype=new Port;
OutputPort.prototype.type="OutputPort";
OutputPort.prototype.onDrop=function(port){
if(this.getMaxFanOut()<=this.getFanOut()){
return;
}
if(this.parentNode.id==port.parentNode.id){
}else{
if(port instanceof InputPort){
var _3581=new CommandConnect(this.parentNode.workflow,this,port);
this.parentNode.workflow.getCommandStack().execute(_3581);
}
}
};
OutputPort.prototype.onDragEnter=function(port){
if(this.getMaxFanOut()<=this.getFanOut()){
return;
}
if(port instanceof InputPort){
Port.prototype.onDragEnter.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof OutputPort){
Port.prototype.onDragEnter.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof OutputPort){
Port.prototype.onDragEnter.call(this,line.getTarget());
}
}
}
}
};
OutputPort.prototype.onDragLeave=function(port){
if(port instanceof InputPort){
Port.prototype.onDragLeave.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof OutputPort){
Port.prototype.onDragLeave.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof OutputPort){
Port.prototype.onDragLeave.call(this,line.getTarget());
}
}
}
}
};
OutputPort.prototype.onDragstart=function(x,y){
if(this.maxFanOut==-1){
return true;
}
if(this.getMaxFanOut()<=this.getFanOut()){
return false;
}
return true;
};
OutputPort.prototype.setMaxFanOut=function(count){
this.maxFanOut=count;
};
OutputPort.prototype.getMaxFanOut=function(){
return this.maxFanOut;
};
OutputPort.prototype.getFanOut=function(){
if(this.getParent().workflow==null){
return 0;
}
var count=0;
var lines=this.getParent().workflow.getLines();
var size=lines.getSize();
for(var i=0;i<size;i++){
var line=lines.get(i);
if(line instanceof Connection){
if(line.getSource()==this){
count++;
}else{
if(line.getTarget()==this){
count++;
}
}
}
}
return count;
};
Line=function(){
this.lineColor=new Color(0,0,0);
this.stroke=1;
this.canvas=null;
this.workflow=null;
this.html=null;
this.graphics=null;
this.id=this.generateUId();
this.startX=30;
this.startY=30;
this.endX=100;
this.endY=100;
this.alpha=1;
this.isMoving=false;
this.zOrder=Line.ZOrderBaseIndex;
this.moveListener=new ArrayList();
this.setSelectable(true);
this.setDeleteable(true);
};
Line.ZOrderBaseIndex=200;
Line.setZOrderBaseIndex=function(index){
Line.ZOrderBaseIndex=index;
};
Line.prototype.dispose=function(){
this.canvas=null;
this.workflow=null;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
Line.prototype.getZOrder=function(){
return this.zOrder;
};
Line.prototype.setZOrder=function(index){
if(this.html!=null){
this.html.style.zIndex=index;
}
this.zOrder=index;
};
Line.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left="0px";
item.style.top="0px";
item.style.height="0px";
item.style.width="0px";
item.style.zIndex=this.zOrder;
return item;
};
Line.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
Line.prototype.getWorkflow=function(){
return this.workflow;
};
Line.prototype.isResizeable=function(){
return true;
};
Line.prototype.setCanvas=function(_3ecb){
this.canvas=_3ecb;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
Line.prototype.setWorkflow=function(_3ecc){
this.workflow=_3ecc;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
Line.prototype.paint=function(){
if(this.graphics==null){
this.graphics=new jsGraphics(this.id);
}else{
this.graphics.clear();
}
this.graphics.setStroke(this.stroke);
this.graphics.setColor(this.lineColor.getHTMLStyle());
this.graphics.drawLine(this.startX,this.startY,this.endX,this.endY);
this.graphics.paint();
};
Line.prototype.attachMoveListener=function(_3ecd){
this.moveListener.add(_3ecd);
};
Line.prototype.detachMoveListener=function(_3ece){
this.moveListener.remove(_3ece);
};
Line.prototype.fireMoveEvent=function(){
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
this.moveListener.get(i).onOtherFigureMoved(this);
}
};
Line.prototype.onOtherFigureMoved=function(_3ed1){
};
Line.prototype.setLineWidth=function(w){
this.stroke=w;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.setColor=function(color){
this.lineColor=color;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.getColor=function(){
return this.lineColor;
};
Line.prototype.setAlpha=function(_3ed4){
if(_3ed4==this.alpha){
return;
}
try{
this.html.style.MozOpacity=_3ed4;
}
catch(exc){
}
try{
this.html.style.opacity=_3ed4;
}
catch(exc){
}
try{
var _3ed5=Math.round(_3ed4*100);
if(_3ed5>=99){
this.html.style.filter="";
}else{
this.html.style.filter="alpha(opacity="+_3ed5+")";
}
}
catch(exc){
}
this.alpha=_3ed4;
};
Line.prototype.setStartPoint=function(x,y){
this.startX=x;
this.startY=y;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.setEndPoint=function(x,y){
this.endX=x;
this.endY=y;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.getStartX=function(){
return this.startX;
};
Line.prototype.getStartY=function(){
return this.startY;
};
Line.prototype.getStartPoint=function(){
return new Point(this.startX,this.startY);
};
Line.prototype.getEndX=function(){
return this.endX;
};
Line.prototype.getEndY=function(){
return this.endY;
};
Line.prototype.getEndPoint=function(){
return new Point(this.endX,this.endY);
};
Line.prototype.isSelectable=function(){
return this.selectable;
};
Line.prototype.setSelectable=function(flag){
this.selectable=flag;
};
Line.prototype.isDeleteable=function(){
return this.deleteable;
};
Line.prototype.setDeleteable=function(flag){
this.deleteable=flag;
};
Line.prototype.getLength=function(){
return Math.sqrt((this.startX-this.endX)*(this.startX-this.endX)+(this.startY-this.endY)*(this.startY-this.endY));
};
Line.prototype.getAngle=function(){
var _3edc=this.getLength();
var angle=-(180/Math.PI)*Math.asin((this.startY-this.endY)/_3edc);
if(angle<0){
if(this.endX<this.startX){
angle=Math.abs(angle)+180;
}else{
angle=360-Math.abs(angle);
}
}else{
if(this.endX<this.startX){
angle=180-angle;
}
}
return angle;
};
Line.prototype.onContextMenu=function(x,y){
var menu=this.getContextMenu();
if(menu!=null){
this.workflow.showMenu(menu,x,y);
}
};
Line.prototype.getContextMenu=function(){
return null;
};
Line.prototype.onDoubleClick=function(){
};
Line.prototype.setDocumentDirty=function(){
if(this.workflow!=null){
this.workflow.setDocumentDirty();
}
};
Line.prototype.generateUId=function(){
var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var _3ee2=10;
var _3ee3=10;
nbTry=0;
while(nbTry<1000){
var id="";
for(var i=0;i<_3ee2;i++){
var rnum=Math.floor(Math.random()*chars.length);
id+=chars.substring(rnum,rnum+1);
}
elem=document.getElementById(id);
if(!elem){
return id;
}
nbTry+=1;
}
return null;
};
Line.prototype.containsPoint=function(px,py){
return Line.hit(this.startX,this.startY,this.endX,this.endY,px,py);
};
Line.hit=function(X1,Y1,X2,Y2,px,py){
var _3eef=5;
X2-=X1;
Y2-=Y1;
px-=X1;
py-=Y1;
var _3ef0=px*X2+py*Y2;
var _3ef1;
if(_3ef0<=0){
_3ef1=0;
}else{
px=X2-px;
py=Y2-py;
_3ef0=px*X2+py*Y2;
if(_3ef0<=0){
_3ef1=0;
}else{
_3ef1=_3ef0*_3ef0/(X2*X2+Y2*Y2);
}
}
var lenSq=px*px+py*py-_3ef1;
if(lenSq<0){
lenSq=0;
}
return Math.sqrt(lenSq)<_3eef;
};
ConnectionRouter=function(){
};
ConnectionRouter.prototype.type="ConnectionRouter";
ConnectionRouter.prototype.getDirection=function(r,p){
var _3f88=Math.abs(r.x-p.x);
var _3f89=3;
var i=Math.abs(r.y-p.y);
if(i<=_3f88){
_3f88=i;
_3f89=0;
}
i=Math.abs(r.getBottom()-p.y);
if(i<=_3f88){
_3f88=i;
_3f89=2;
}
i=Math.abs(r.getRight()-p.x);
if(i<_3f88){
_3f88=i;
_3f89=1;
}
return _3f89;
};
ConnectionRouter.prototype.getEndDirection=function(conn){
var p=conn.getEndPoint();
var rect=conn.getTarget().getParent().getBounds();
return this.getDirection(rect,p);
};
ConnectionRouter.prototype.getStartDirection=function(conn){
var p=conn.getStartPoint();
var rect=conn.getSource().getParent().getBounds();
return this.getDirection(rect,p);
};
ConnectionRouter.prototype.route=function(_3f91){
};
NullConnectionRouter=function(){
};
NullConnectionRouter.prototype=new ConnectionRouter;
NullConnectionRouter.prototype.type="NullConnectionRouter";
NullConnectionRouter.prototype.invalidate=function(){
};
NullConnectionRouter.prototype.route=function(_3f6a){
_3f6a.addPoint(_3f6a.getStartPoint());
_3f6a.addPoint(_3f6a.getEndPoint());
};
ManhattanConnectionRouter=function(){
this.MINDIST=20;
};
ManhattanConnectionRouter.prototype=new ConnectionRouter;
ManhattanConnectionRouter.prototype.type="ManhattanConnectionRouter";
ManhattanConnectionRouter.prototype.route=function(conn){
var _3ba8=conn.getStartPoint();
var _3ba9=this.getStartDirection(conn);
var toPt=conn.getEndPoint();
var toDir=this.getEndDirection(conn);
this._route(conn,toPt,toDir,_3ba8,_3ba9);
};
ManhattanConnectionRouter.prototype._route=function(conn,_3bad,_3bae,toPt,toDir){
var TOL=0.1;
var _3bb2=0.01;
var UP=0;
var RIGHT=1;
var DOWN=2;
var LEFT=3;
var xDiff=_3bad.x-toPt.x;
var yDiff=_3bad.y-toPt.y;
var point;
var dir;
if(((xDiff*xDiff)<(_3bb2))&&((yDiff*yDiff)<(_3bb2))){
conn.addPoint(new Point(toPt.x,toPt.y));
return;
}
if(_3bae==LEFT){
if((xDiff>0)&&((yDiff*yDiff)<TOL)&&(toDir==RIGHT)){
point=toPt;
dir=toDir;
}else{
if(xDiff<0){
point=new Point(_3bad.x-this.MINDIST,_3bad.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_3bad.y);
}else{
if(_3bae==toDir){
var pos=Math.min(_3bad.x,toPt.x)-this.MINDIST;
point=new Point(pos,_3bad.y);
}else{
point=new Point(_3bad.x-(xDiff/2),_3bad.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_3bae==RIGHT){
if((xDiff<0)&&((yDiff*yDiff)<TOL)&&(toDir==LEFT)){
point=toPt;
dir=toDir;
}else{
if(xDiff>0){
point=new Point(_3bad.x+this.MINDIST,_3bad.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_3bad.y);
}else{
if(_3bae==toDir){
var pos=Math.max(_3bad.x,toPt.x)+this.MINDIST;
point=new Point(pos,_3bad.y);
}else{
point=new Point(_3bad.x-(xDiff/2),_3bad.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_3bae==DOWN){
if(((xDiff*xDiff)<TOL)&&(yDiff<0)&&(toDir==UP)){
point=toPt;
dir=toDir;
}else{
if(yDiff>0){
point=new Point(_3bad.x,_3bad.y+this.MINDIST);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_3bad.x,toPt.y);
}else{
if(_3bae==toDir){
var pos=Math.max(_3bad.y,toPt.y)+this.MINDIST;
point=new Point(_3bad.x,pos);
}else{
point=new Point(_3bad.x,_3bad.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}else{
if(_3bae==UP){
if(((xDiff*xDiff)<TOL)&&(yDiff>0)&&(toDir==DOWN)){
point=toPt;
dir=toDir;
}else{
if(yDiff<0){
point=new Point(_3bad.x,_3bad.y-this.MINDIST);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_3bad.x,toPt.y);
}else{
if(_3bae==toDir){
var pos=Math.min(_3bad.y,toPt.y)-this.MINDIST;
point=new Point(_3bad.x,pos);
}else{
point=new Point(_3bad.x,_3bad.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}
}
}
}
this._route(conn,point,dir,toPt,toDir);
conn.addPoint(_3bad);
};
BezierConnectionRouter=function(_354a){
if(!_354a){
this.cheapRouter=new ManhattanConnectionRouter();
}else{
this.cheapRouter=null;
}
this.iteration=5;
};
BezierConnectionRouter.prototype=new ConnectionRouter;
BezierConnectionRouter.prototype.type="BezierConnectionRouter";
BezierConnectionRouter.prototype.drawBezier=function(_354b,_354c,t,iter){
var n=_354b.length-1;
var q=new Array();
var _3551=n+1;
for(var i=0;i<_3551;i++){
q[i]=new Array();
q[i][0]=_354b[i];
}
for(var j=1;j<=n;j++){
for(var i=0;i<=(n-j);i++){
q[i][j]=new Point((1-t)*q[i][j-1].x+t*q[i+1][j-1].x,(1-t)*q[i][j-1].y+t*q[i+1][j-1].y);
}
}
var c1=new Array();
var c2=new Array();
for(var i=0;i<n+1;i++){
c1[i]=q[0][i];
c2[i]=q[i][n-i];
}
if(iter>=0){
this.drawBezier(c1,_354c,t,--iter);
this.drawBezier(c2,_354c,t,--iter);
}else{
for(var i=0;i<n;i++){
_354c.push(q[i][n-i]);
}
}
};
BezierConnectionRouter.prototype.route=function(conn){
if(this.cheapRouter!=null&&(conn.getSource().getParent().isMoving==true||conn.getTarget().getParent().isMoving==true)){
this.cheapRouter.route(conn);
return;
}
var _3557=new Array();
var _3558=conn.getStartPoint();
var toPt=conn.getEndPoint();
this._route(_3557,conn,toPt,this.getEndDirection(conn),_3558,this.getStartDirection(conn));
var _355a=new Array();
this.drawBezier(_3557,_355a,0.5,this.iteration);
for(var i=0;i<_355a.length;i++){
conn.addPoint(_355a[i]);
}
conn.addPoint(toPt);
};
BezierConnectionRouter.prototype._route=function(_355c,conn,_355e,_355f,toPt,toDir){
var TOL=0.1;
var _3563=0.01;
var _3564=90;
var UP=0;
var RIGHT=1;
var DOWN=2;
var LEFT=3;
var xDiff=_355e.x-toPt.x;
var yDiff=_355e.y-toPt.y;
var point;
var dir;
if(((xDiff*xDiff)<(_3563))&&((yDiff*yDiff)<(_3563))){
_355c.push(new Point(toPt.x,toPt.y));
return;
}
if(_355f==LEFT){
if((xDiff>0)&&((yDiff*yDiff)<TOL)&&(toDir==RIGHT)){
point=toPt;
dir=toDir;
}else{
if(xDiff<0){
point=new Point(_355e.x-_3564,_355e.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_355e.y);
}else{
if(_355f==toDir){
var pos=Math.min(_355e.x,toPt.x)-_3564;
point=new Point(pos,_355e.y);
}else{
point=new Point(_355e.x-(xDiff/2),_355e.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_355f==RIGHT){
if((xDiff<0)&&((yDiff*yDiff)<TOL)&&(toDir==LEFT)){
point=toPt;
dir=toDir;
}else{
if(xDiff>0){
point=new Point(_355e.x+_3564,_355e.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_355e.y);
}else{
if(_355f==toDir){
var pos=Math.max(_355e.x,toPt.x)+_3564;
point=new Point(pos,_355e.y);
}else{
point=new Point(_355e.x-(xDiff/2),_355e.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_355f==DOWN){
if(((xDiff*xDiff)<TOL)&&(yDiff<0)&&(toDir==UP)){
point=toPt;
dir=toDir;
}else{
if(yDiff>0){
point=new Point(_355e.x,_355e.y+_3564);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_355e.x,toPt.y);
}else{
if(_355f==toDir){
var pos=Math.max(_355e.y,toPt.y)+_3564;
point=new Point(_355e.x,pos);
}else{
point=new Point(_355e.x,_355e.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}else{
if(_355f==UP){
if(((xDiff*xDiff)<TOL)&&(yDiff>0)&&(toDir==DOWN)){
point=toPt;
dir=toDir;
}else{
if(yDiff<0){
point=new Point(_355e.x,_355e.y-_3564);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_355e.x,toPt.y);
}else{
if(_355f==toDir){
var pos=Math.min(_355e.y,toPt.y)-_3564;
point=new Point(_355e.x,pos);
}else{
point=new Point(_355e.x,_355e.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}
}
}
}
this._route(_355c,conn,point,dir,toPt,toDir);
_355c.push(_355e);
};
FanConnectionRouter=function(){
};
FanConnectionRouter.prototype=new NullConnectionRouter;
FanConnectionRouter.prototype.type="FanConnectionRouter";
FanConnectionRouter.prototype.route=function(conn){
var _40c7=conn.getStartPoint();
var toPt=conn.getEndPoint();
var lines=conn.getSource().getConnections();
var _40ca=new ArrayList();
var index=0;
for(var i=0;i<lines.getSize();i++){
var _40cd=lines.get(i);
if(_40cd.getTarget()==conn.getTarget()||_40cd.getSource()==conn.getTarget()){
_40ca.add(_40cd);
if(conn==_40cd){
index=_40ca.getSize();
}
}
}
if(_40ca.getSize()>1){
this.routeCollision(conn,index);
}else{
NullConnectionRouter.prototype.route.call(this,conn);
}
};
FanConnectionRouter.prototype.routeNormal=function(conn){
conn.addPoint(conn.getStartPoint());
conn.addPoint(conn.getEndPoint());
};
FanConnectionRouter.prototype.routeCollision=function(conn,index){
var start=conn.getStartPoint();
var end=conn.getEndPoint();
conn.addPoint(start);
var _40d3=10;
var _40d4=new Point((end.x+start.x)/2,(end.y+start.y)/2);
var _40d5=end.getPosition(start);
var ray;
if(_40d5==PositionConstants.SOUTH||_40d5==PositionConstants.EAST){
ray=new Point(end.x-start.x,end.y-start.y);
}else{
ray=new Point(start.x-end.x,start.y-end.y);
}
var _40d7=Math.sqrt(ray.x*ray.x+ray.y*ray.y);
var _40d8=_40d3*ray.x/_40d7;
var _40d9=_40d3*ray.y/_40d7;
var _40da;
if(index%2==0){
_40da=new Point(_40d4.x+(index/2)*(-1*_40d9),_40d4.y+(index/2)*_40d8);
}else{
_40da=new Point(_40d4.x+(index/2)*_40d9,_40d4.y+(index/2)*(-1*_40d8));
}
conn.addPoint(_40da);
conn.addPoint(end);
};
Graphics=function(_3a61,_3a62,_3a63){
this.jsGraphics=_3a61;
this.xt=_3a63.x;
this.yt=_3a63.y;
this.radian=_3a62*Math.PI/180;
this.sinRadian=Math.sin(this.radian);
this.cosRadian=Math.cos(this.radian);
};
Graphics.prototype.setStroke=function(x){
this.jsGraphics.setStroke(x);
};
Graphics.prototype.drawLine=function(x1,y1,x2,y2){
var _x1=this.xt+x1*this.cosRadian-y1*this.sinRadian;
var _y1=this.yt+x1*this.sinRadian+y1*this.cosRadian;
var _x2=this.xt+x2*this.cosRadian-y2*this.sinRadian;
var _y2=this.yt+x2*this.sinRadian+y2*this.cosRadian;
this.jsGraphics.drawLine(_x1,_y1,_x2,_y2);
};
Graphics.prototype.fillRect=function(x,y,w,h){
var x1=this.xt+x*this.cosRadian-y*this.sinRadian;
var y1=this.yt+x*this.sinRadian+y*this.cosRadian;
var x2=this.xt+(x+w)*this.cosRadian-y*this.sinRadian;
var y2=this.yt+(x+w)*this.sinRadian+y*this.cosRadian;
var x3=this.xt+(x+w)*this.cosRadian-(y+h)*this.sinRadian;
var y3=this.yt+(x+w)*this.sinRadian+(y+h)*this.cosRadian;
var x4=this.xt+x*this.cosRadian-(y+h)*this.sinRadian;
var y4=this.yt+x*this.sinRadian+(y+h)*this.cosRadian;
this.jsGraphics.fillPolygon([x1,x2,x3,x4],[y1,y2,y3,y4]);
};
Graphics.prototype.fillPolygon=function(_3a79,_3a7a){
var rotX=new Array();
var rotY=new Array();
for(var i=0;i<_3a79.length;i++){
rotX[i]=this.xt+_3a79[i]*this.cosRadian-_3a7a[i]*this.sinRadian;
rotY[i]=this.yt+_3a79[i]*this.sinRadian+_3a7a[i]*this.cosRadian;
}
this.jsGraphics.fillPolygon(rotX,rotY);
};
Graphics.prototype.setColor=function(color){
this.jsGraphics.setColor(color.getHTMLStyle());
};
Graphics.prototype.drawPolygon=function(_3a7f,_3a80){
var rotX=new Array();
var rotY=new Array();
for(var i=0;i<_3a7f.length;i++){
rotX[i]=this.xt+_3a7f[i]*this.cosRadian-_3a80[i]*this.sinRadian;
rotY[i]=this.yt+_3a7f[i]*this.sinRadian+_3a80[i]*this.cosRadian;
}
this.jsGraphics.drawPolygon(rotX,rotY);
};
Connection=function(){
Line.call(this);
this.sourcePort=null;
this.targetPort=null;
this.sourceDecorator=null;
this.targetDecorator=null;
this.sourceAnchor=new ConnectionAnchor();
this.targetAnchor=new ConnectionAnchor();
this.router=Connection.defaultRouter;
this.lineSegments=new ArrayList();
this.children=new ArrayList();
this.setColor(new Color(0,0,115));
this.setLineWidth(1);
};
Connection.prototype=new Line;
Connection.defaultRouter=new ManhattanConnectionRouter();
Connection.setDefaultRouter=function(_2e24){
Connection.defaultRouter=_2e24;
};
Connection.prototype.disconnect=function(){
if(this.sourcePort!=null){
this.sourcePort.detachMoveListener(this);
this.fireSourcePortRouteEvent();
}
if(this.targetPort!=null){
this.targetPort.detachMoveListener(this);
this.fireTargetPortRouteEvent();
}
};
Connection.prototype.reconnect=function(){
if(this.sourcePort!=null){
this.sourcePort.attachMoveListener(this);
this.fireSourcePortRouteEvent();
}
if(this.targetPort!=null){
this.targetPort.attachMoveListener(this);
this.fireTargetPortRouteEvent();
}
};
Connection.prototype.isResizeable=function(){
return true;
};
Connection.prototype.addFigure=function(_2e25,_2e26){
var entry=new Object();
entry.figure=_2e25;
entry.locator=_2e26;
this.children.add(entry);
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setSourceDecorator=function(_2e28){
this.sourceDecorator=_2e28;
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setTargetDecorator=function(_2e29){
this.targetDecorator=_2e29;
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setSourceAnchor=function(_2e2a){
this.sourceAnchor=_2e2a;
this.sourceAnchor.setOwner(this.sourcePort);
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setTargetAnchor=function(_2e2b){
this.targetAnchor=_2e2b;
this.targetAnchor.setOwner(this.targetPort);
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setRouter=function(_2e2c){
if(_2e2c!=null){
this.router=_2e2c;
}else{
this.router=new NullConnectionRouter();
}
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.getRouter=function(){
return this.router;
};
Connection.prototype.paint=function(){
for(var i=0;i<this.children.getSize();i++){
var entry=this.children.get(i);
if(entry.isAppended==true){
this.html.removeChild(entry.figure.getHTMLElement());
}
entry.isAppended=false;
}
if(this.graphics==null){
this.graphics=new jsGraphics(this.id);
}else{
this.graphics.clear();
}
this.graphics.setStroke(this.stroke);
this.graphics.setColor(this.lineColor.getHTMLStyle());
this.startStroke();
this.router.route(this);
if(this.getSource().getParent().isMoving==false&&this.getTarget().getParent().isMoving==false){
if(this.targetDecorator!=null){
this.targetDecorator.paint(new Graphics(this.graphics,this.getEndAngle(),this.getEndPoint()));
}
if(this.sourceDecorator!=null){
this.sourceDecorator.paint(new Graphics(this.graphics,this.getStartAngle(),this.getStartPoint()));
}
}
this.finishStroke();
for(var i=0;i<this.children.getSize();i++){
var entry=this.children.get(i);
this.html.appendChild(entry.figure.getHTMLElement());
entry.isAppended=true;
entry.locator.relocate(entry.figure);
}
};
Connection.prototype.getStartPoint=function(){
if(this.isMoving==false){
return this.sourceAnchor.getLocation(this.targetAnchor.getReferencePoint());
}else{
return Line.prototype.getStartPoint.call(this);
}
};
Connection.prototype.getEndPoint=function(){
if(this.isMoving==false){
return this.targetAnchor.getLocation(this.sourceAnchor.getReferencePoint());
}else{
return Line.prototype.getEndPoint.call(this);
}
};
Connection.prototype.startStroke=function(){
this.oldPoint=null;
this.lineSegments=new ArrayList();
};
Connection.prototype.finishStroke=function(){
this.graphics.paint();
this.oldPoint=null;
};
Connection.prototype.getPoints=function(){
var _2e2f=new ArrayList();
var line;
for(var i=0;i<this.lineSegments.getSize();i++){
line=this.lineSegments.get(i);
_2e2f.add(line.start);
}
_2e2f.add(line.end);
return _2e2f;
};
Connection.prototype.addPoint=function(p){
p=new Point(parseInt(p.x),parseInt(p.y));
if(this.oldPoint!=null){
this.graphics.drawLine(this.oldPoint.x,this.oldPoint.y,p.x,p.y);
var line=new Object();
line.start=this.oldPoint;
line.end=p;
this.lineSegments.add(line);
}
this.oldPoint=new Object();
this.oldPoint.x=p.x;
this.oldPoint.y=p.y;
};
Connection.prototype.setSource=function(port){
if(this.sourcePort!=null){
this.sourcePort.detachMoveListener(this);
}
this.sourcePort=port;
if(this.sourcePort==null){
return;
}
this.sourceAnchor.setOwner(this.sourcePort);
this.fireSourcePortRouteEvent();
this.sourcePort.attachMoveListener(this);
this.setStartPoint(port.getAbsoluteX(),port.getAbsoluteY());
};
Connection.prototype.getSource=function(){
return this.sourcePort;
};
Connection.prototype.setTarget=function(port){
if(this.targetPort!=null){
this.targetPort.detachMoveListener(this);
}
this.targetPort=port;
if(this.targetPort==null){
return;
}
this.targetAnchor.setOwner(this.targetPort);
this.fireTargetPortRouteEvent();
this.targetPort.attachMoveListener(this);
this.setEndPoint(port.getAbsoluteX(),port.getAbsoluteY());
};
Connection.prototype.getTarget=function(){
return this.targetPort;
};
Connection.prototype.onOtherFigureMoved=function(_2e36){
if(_2e36==this.sourcePort){
this.setStartPoint(this.sourcePort.getAbsoluteX(),this.sourcePort.getAbsoluteY());
}else{
this.setEndPoint(this.targetPort.getAbsoluteX(),this.targetPort.getAbsoluteY());
}
};
Connection.prototype.containsPoint=function(px,py){
for(var i=0;i<this.lineSegments.getSize();i++){
var line=this.lineSegments.get(i);
if(Line.hit(line.start.x,line.start.y,line.end.x,line.end.y,px,py)){
return true;
}
}
return false;
};
Connection.prototype.getStartAngle=function(){
var p1=this.lineSegments.get(0).start;
var p2=this.lineSegments.get(0).end;
if(this.router instanceof BezierConnectionRouter){
p2=this.lineSegments.get(5).end;
}
var _2e3d=Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
var angle=-(180/Math.PI)*Math.asin((p1.y-p2.y)/_2e3d);
if(angle<0){
if(p2.x<p1.x){
angle=Math.abs(angle)+180;
}else{
angle=360-Math.abs(angle);
}
}else{
if(p2.x<p1.x){
angle=180-angle;
}
}
return angle;
};
Connection.prototype.getEndAngle=function(){
var p1=this.lineSegments.get(this.lineSegments.getSize()-1).end;
var p2=this.lineSegments.get(this.lineSegments.getSize()-1).start;
if(this.router instanceof BezierConnectionRouter){
p2=this.lineSegments.get(this.lineSegments.getSize()-5).end;
}
var _2e41=Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
var angle=-(180/Math.PI)*Math.asin((p1.y-p2.y)/_2e41);
if(angle<0){
if(p2.x<p1.x){
angle=Math.abs(angle)+180;
}else{
angle=360-Math.abs(angle);
}
}else{
if(p2.x<p1.x){
angle=180-angle;
}
}
return angle;
};
Connection.prototype.fireSourcePortRouteEvent=function(){
var _2e43=this.sourcePort.getConnections();
for(var i=0;i<_2e43.getSize();i++){
_2e43.get(i).paint();
}
};
Connection.prototype.fireTargetPortRouteEvent=function(){
var _2e45=this.targetPort.getConnections();
for(var i=0;i<_2e45.getSize();i++){
_2e45.get(i).paint();
}
};
ConnectionAnchor=function(owner){
this.owner=owner;
};
ConnectionAnchor.prototype.type="ConnectionAnchor";
ConnectionAnchor.prototype.getLocation=function(_40c2){
return this.getReferencePoint();
};
ConnectionAnchor.prototype.getOwner=function(){
return this.owner;
};
ConnectionAnchor.prototype.setOwner=function(owner){
this.owner=owner;
};
ConnectionAnchor.prototype.getBox=function(){
return this.getOwner().getAbsoluteBounds();
};
ConnectionAnchor.prototype.getReferencePoint=function(){
if(this.getOwner()==null){
return null;
}else{
return this.getOwner().getAbsolutePosition();
}
};
ChopboxConnectionAnchor=function(owner){
ConnectionAnchor.call(this,owner);
};
ChopboxConnectionAnchor.prototype=new ConnectionAnchor;
ChopboxConnectionAnchor.prototype.type="ChopboxConnectionAnchor";
ChopboxConnectionAnchor.prototype.getLocation=function(_3854){
var r=new Dimension();
r.setBounds(this.getBox());
r.translate(-1,-1);
r.resize(1,1);
var _3856=r.x+r.w/2;
var _3857=r.y+r.h/2;
if(r.isEmpty()||(_3854.x==_3856&&_3854.y==_3857)){
return new Point(_3856,_3857);
}
var dx=_3854.x-_3856;
var dy=_3854.y-_3857;
var scale=0.5/Math.max(Math.abs(dx)/r.w,Math.abs(dy)/r.h);
dx*=scale;
dy*=scale;
_3856+=dx;
_3857+=dy;
return new Point(Math.round(_3856),Math.round(_3857));
};
ChopboxConnectionAnchor.prototype.getBox=function(){
return this.getOwner().getParent().getBounds();
};
ChopboxConnectionAnchor.prototype.getReferencePoint=function(){
return this.getBox().getCenter();
};
ConnectionDecorator=function(){
this.color=new Color(0,0,0);
this.backgroundColor=new Color(250,250,250);
};
ConnectionDecorator.prototype.type="ConnectionDecorator";
ConnectionDecorator.prototype.paint=function(g){
};
ConnectionDecorator.prototype.setColor=function(c){
this.color=c;
};
ConnectionDecorator.prototype.setBackgroundColor=function(c){
this.backgroundColor=c;
};
ArrowConnectionDecorator=function(){
};
ArrowConnectionDecorator.prototype=new ConnectionDecorator;
ArrowConnectionDecorator.prototype.type="ArrowConnectionDecorator";
ArrowConnectionDecorator.prototype.paint=function(g){
if(this.backgroundColor!=null){
g.setColor(this.backgroundColor);
g.fillPolygon([1,10,10,1],[0,5,-5,0]);
}
g.setColor(this.color);
g.setStroke(1);
g.drawPolygon([1,10,10,1],[0,5,-5,0]);
g.fillPolygon([1,10,10,1],[0,5,-5,0]);
};
CompartmentFigure=function(){
Node.call(this);
this.children=new ArrayList();
this.setBorder(new LineBorder(1));
this.dropable=new DropTarget(this.html);
this.dropable.node=this;
this.dropable.addEventListener("figureenter",function(_4072){
_4072.target.node.onFigureEnter(_4072.relatedTarget.node);
});
this.dropable.addEventListener("figureleave",function(_4073){
_4073.target.node.onFigureLeave(_4073.relatedTarget.node);
});
this.dropable.addEventListener("figuredrop",function(_4074){
_4074.target.node.onFigureDrop(_4074.relatedTarget.node);
});
};
CompartmentFigure.prototype=new Node;
CompartmentFigure.prototype.type="CompartmentFigure";
CompartmentFigure.prototype.onFigureEnter=function(_4075){
};
CompartmentFigure.prototype.onFigureLeave=function(_4076){
};
CompartmentFigure.prototype.onFigureDrop=function(_4077){
};
CompartmentFigure.prototype.getChildren=function(){
return this.children;
};
CompartmentFigure.prototype.addChild=function(_4078){
_4078.setZOrder(this.getZOrder()+1);
_4078.setParent(this);
this.children.add(_4078);
};
CompartmentFigure.prototype.removeChild=function(_4079){
_4079.setParent(null);
this.children.remove(_4079);
};
CompartmentFigure.prototype.setZOrder=function(index){
Node.prototype.setZOrder.call(this,index);
for(var i=0;i<this.children.getSize();i++){
this.children.get(i).setZOrder(index+1);
}
};
CompartmentFigure.prototype.setPosition=function(xPos,yPos){
var oldX=this.getX();
var oldY=this.getY();
Node.prototype.setPosition.call(this,xPos,yPos);
for(var i=0;i<this.children.getSize();i++){
var child=this.children.get(i);
child.setPosition(child.getX()+this.getX()-oldX,child.getY()+this.getY()-oldY);
}
};
CompartmentFigure.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Node.prototype.onDrag.call(this);
for(var i=0;i<this.children.getSize();i++){
var child=this.children.get(i);
child.setPosition(child.getX()+this.getX()-oldX,child.getY()+this.getY()-oldY);
}
};
Document=function(_3a3b){
this.canvas=_3a3b;
};
Document.prototype.getFigures=function(){
var _3a3c=new ArrayList();
var _3a3d=this.canvas.figures;
var _3a3e=this.canvas.dialogs;
for(var i=0;i<_3a3d.getSize();i++){
var _3a40=_3a3d.get(i);
if(_3a3e.indexOf(_3a40)==-1&&_3a40.getParent()==null&&!(_3a40 instanceof Window)){
_3a3c.add(_3a40);
}
}
return _3a3c;
};
Document.prototype.getFigure=function(id){
return this.canvas.getFigure(id);
};
Document.prototype.getLines=function(){
return this.canvas.getLines();
};
Annotation=function(msg){
this.msg=msg;
this.color=new Color(0,0,0);
this.bgColor=new Color(241,241,121);
this.fontSize=10;
this.textNode=null;
Figure.call(this);
};
Annotation.prototype=new Figure;
Annotation.prototype.type="Annotation";
Annotation.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.color=this.color.getHTMLStyle();
item.style.backgroundColor=this.bgColor.getHTMLStyle();
item.style.fontSize=this.fontSize+"pt";
item.style.width="auto";
item.style.height="auto";
item.style.margin="0px";
item.style.padding="0px";
item.onselectstart=function(){
return false;
};
item.unselectable="on";
item.style.MozUserSelect="none";
item.style.cursor="default";
this.textNode=document.createTextNode(this.msg);
item.appendChild(this.textNode);
this.disableTextSelection(item);
return item;
};
Annotation.prototype.onDoubleClick=function(){
var _409d=new AnnotationDialog(this);
this.workflow.showDialog(_409d);
};
Annotation.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Annotation.prototype.getBackgroundColor=function(){
return this.bgColor;
};
Annotation.prototype.setFontSize=function(size){
this.fontSize=size;
this.html.style.fontSize=this.fontSize+"pt";
};
Annotation.prototype.getText=function(){
return this.msg;
};
Annotation.prototype.setText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createTextNode(this.msg);
this.html.appendChild(this.textNode);
};
Annotation.prototype.setStyledText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createElement("div");
this.textNode.innerHTML=text;
this.html.appendChild(this.textNode);
};
ResizeHandle=function(_2d2f,type){
Rectangle.call(this,5,5);
this.type=type;
var _2d31=this.getWidth();
var _2d32=_2d31/2;
switch(this.type){
case 1:
this.setSnapToGridAnchor(new Point(_2d31,_2d31));
break;
case 2:
this.setSnapToGridAnchor(new Point(_2d32,_2d31));
break;
case 3:
this.setSnapToGridAnchor(new Point(0,_2d31));
break;
case 4:
this.setSnapToGridAnchor(new Point(0,_2d32));
break;
case 5:
this.setSnapToGridAnchor(new Point(0,0));
break;
case 6:
this.setSnapToGridAnchor(new Point(_2d32,0));
break;
case 7:
this.setSnapToGridAnchor(new Point(_2d31,0));
break;
case 8:
this.setSnapToGridAnchor(new Point(_2d31,_2d32));
break;
}
this.setBackgroundColor(new Color(0,255,0));
this.setWorkflow(_2d2f);
this.setZOrder(10000);
};
ResizeHandle.prototype=new Rectangle;
ResizeHandle.prototype.type="ResizeHandle";
ResizeHandle.prototype.getSnapToDirection=function(){
switch(this.type){
case 1:
return SnapToHelper.NORTH_WEST;
case 2:
return SnapToHelper.NORTH;
case 3:
return SnapToHelper.NORTH_EAST;
case 4:
return SnapToHelper.EAST;
case 5:
return SnapToHelper.SOUTH_EAST;
case 6:
return SnapToHelper.SOUTH;
case 7:
return SnapToHelper.SOUTH_WEST;
case 8:
return SnapToHelper.WEST;
}
};
ResizeHandle.prototype.onDragend=function(){
if(this.commandMove==null){
return;
}
var _2d33=this.workflow.currentSelection;
this.commandMove.setPosition(_2d33.getX(),_2d33.getY());
this.commandResize.setDimension(_2d33.getWidth(),_2d33.getHeight());
this.workflow.getCommandStack().execute(this.commandResize);
this.workflow.getCommandStack().execute(this.commandMove);
this.commandMove=null;
this.commandResize=null;
this.workflow.hideSnapToHelperLines();
};
ResizeHandle.prototype.setPosition=function(xPos,yPos){
this.x=xPos;
this.y=yPos;
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
};
ResizeHandle.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
var _2d38=this.workflow.currentSelection;
this.commandMove=new CommandMove(_2d38,_2d38.getX(),_2d38.getY());
this.commandResize=new CommandResize(_2d38,_2d38.getWidth(),_2d38.getHeight());
return true;
};
ResizeHandle.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Rectangle.prototype.onDrag.call(this);
var diffX=oldX-this.getX();
var diffY=oldY-this.getY();
var _2d3d=this.workflow.currentSelection.getX();
var _2d3e=this.workflow.currentSelection.getY();
var _2d3f=this.workflow.currentSelection.getWidth();
var _2d40=this.workflow.currentSelection.getHeight();
switch(this.type){
case 1:
this.workflow.currentSelection.setPosition(_2d3d-diffX,_2d3e-diffY);
this.workflow.currentSelection.setDimension(_2d3f+diffX,_2d40+diffY);
break;
case 2:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e-diffY);
this.workflow.currentSelection.setDimension(_2d3f,_2d40+diffY);
break;
case 3:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e-diffY);
this.workflow.currentSelection.setDimension(_2d3f-diffX,_2d40+diffY);
break;
case 4:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f-diffX,_2d40);
break;
case 5:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f-diffX,_2d40-diffY);
break;
case 6:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f,_2d40-diffY);
break;
case 7:
this.workflow.currentSelection.setPosition(_2d3d-diffX,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f+diffX,_2d40-diffY);
break;
case 8:
this.workflow.currentSelection.setPosition(_2d3d-diffX,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f+diffX,_2d40);
break;
}
this.workflow.moveResizeHandles(this.workflow.getCurrentSelection());
};
ResizeHandle.prototype.setCanDrag=function(flag){
Rectangle.prototype.setCanDrag.call(this,flag);
if(!flag){
this.html.style.cursor="";
return;
}
switch(this.type){
case 1:
this.html.style.cursor="nw-resize";
break;
case 2:
this.html.style.cursor="s-resize";
break;
case 3:
this.html.style.cursor="ne-resize";
break;
case 4:
this.html.style.cursor="w-resize";
break;
case 5:
this.html.style.cursor="se-resize";
break;
case 6:
this.html.style.cursor="n-resize";
break;
case 7:
this.html.style.cursor="sw-resize";
break;
case 8:
this.html.style.cursor="e-resize";
break;
}
};
ResizeHandle.prototype.onKeyDown=function(_2d42,ctrl){
this.workflow.onKeyDown(_2d42,ctrl);
};
ResizeHandle.prototype.fireMoveEvent=function(){
};
LineStartResizeHandle=function(_40f9){
Rectangle.call(this);
this.setDimension(10,10);
this.setBackgroundColor(new Color(0,255,0));
this.setWorkflow(_40f9);
this.setZOrder(10000);
};
LineStartResizeHandle.prototype=new Rectangle;
LineStartResizeHandle.prototype.type="LineStartResizeHandle";
LineStartResizeHandle.prototype.onDragend=function(){
var line=this.workflow.currentSelection;
if(line instanceof Connection){
var start=line.sourceAnchor.getLocation(line.targetAnchor.getReferencePoint());
line.setStartPoint(start.x,start.y);
this.getWorkflow().showLineResizeHandles(line);
line.setRouter(line.oldRouter);
}else{
if(this.command==null){
return;
}
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command.setEndPoints(x1,y1,x2,y2);
this.getWorkflow().getCommandStack().execute(this.command);
this.command=null;
}
};
LineStartResizeHandle.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
var line=this.workflow.currentSelection;
if(line instanceof Connection){
this.command=new CommandReconnect(line);
line.oldRouter=line.getRouter();
line.setRouter(new NullConnectionRouter());
}else{
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command=new CommandMoveLine(line,x1,y1,x2,y2);
}
return true;
};
LineStartResizeHandle.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Rectangle.prototype.onDrag.call(this);
var diffX=oldX-this.getX();
var diffY=oldY-this.getY();
var _410b=this.workflow.currentSelection.getStartPoint();
var line=this.workflow.currentSelection;
line.setStartPoint(_410b.x-diffX,_410b.y-diffY);
line.isMoving=true;
};
LineStartResizeHandle.prototype.onDrop=function(_410d){
var line=this.workflow.currentSelection;
line.isMoving=false;
if(line instanceof Connection){
this.command.setNewPorts(_410d,line.getTarget());
this.getWorkflow().getCommandStack().execute(this.command);
}
this.command=null;
};
LineStartResizeHandle.prototype.onKeyDown=function(_410f,ctrl){
if(this.workflow!=null){
this.workflow.onKeyDown(_410f,ctrl);
}
};
LineStartResizeHandle.prototype.fireMoveEvent=function(){
};
LineEndResizeHandle=function(_3f2a){
Rectangle.call(this);
this.setDimension(10,10);
this.setBackgroundColor(new Color(0,255,0));
this.setWorkflow(_3f2a);
this.setZOrder(10000);
};
LineEndResizeHandle.prototype=new Rectangle;
LineEndResizeHandle.prototype.type="LineEndResizeHandle";
LineEndResizeHandle.prototype.onDragend=function(){
var line=this.workflow.currentSelection;
if(line instanceof Connection){
var end=line.targetAnchor.getLocation(line.sourceAnchor.getReferencePoint());
line.setEndPoint(end.x,end.y);
this.getWorkflow().showLineResizeHandles(line);
line.setRouter(line.oldRouter);
}else{
if(this.command==null){
return;
}
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command.setEndPoints(x1,y1,x2,y2);
this.workflow.getCommandStack().execute(this.command);
this.command=null;
}
};
LineEndResizeHandle.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
var line=this.workflow.currentSelection;
if(line instanceof Connection){
this.command=new CommandReconnect(line);
line.oldRouter=line.getRouter();
line.setRouter(new NullConnectionRouter());
}else{
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command=new CommandMoveLine(line,x1,y1,x2,y2);
}
return true;
};
LineEndResizeHandle.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Rectangle.prototype.onDrag.call(this);
var diffX=oldX-this.getX();
var diffY=oldY-this.getY();
var _3f3c=this.workflow.currentSelection.getEndPoint();
var line=this.workflow.currentSelection;
line.setEndPoint(_3f3c.x-diffX,_3f3c.y-diffY);
line.isMoving=true;
};
LineEndResizeHandle.prototype.onDrop=function(_3f3e){
var line=this.workflow.currentSelection;
line.isMoving=false;
if(line instanceof Connection){
this.command.setNewPorts(line.getSource(),_3f3e);
this.getWorkflow().getCommandStack().execute(this.command);
}
this.command=null;
};
LineEndResizeHandle.prototype.onKeyDown=function(_3f40){
if(this.workflow!=null){
this.workflow.onKeyDown(_3f40);
}
};
LineEndResizeHandle.prototype.fireMoveEvent=function(){
};
Canvas=function(_3e59){
if(_3e59){
this.construct(_3e59);
}
this.enableSmoothFigureHandling=false;
this.canvasLines=new ArrayList();
};
Canvas.prototype.type="Canvas";
Canvas.prototype.construct=function(_3e5a){
this.canvasId=_3e5a;
this.html=document.getElementById(this.canvasId);
this.scrollArea=document.body.parentNode;
};
Canvas.prototype.setViewPort=function(divId){
this.scrollArea=document.getElementById(divId);
};
Canvas.prototype.addFigure=function(_3e5c,xPos,yPos,_3e5f){
if(this.enableSmoothFigureHandling==true){
if(_3e5c.timer<=0){
_3e5c.setAlpha(0.001);
}
var _3e60=_3e5c;
var _3e61=function(){
if(_3e60.alpha<1){
_3e60.setAlpha(Math.min(1,_3e60.alpha+0.05));
}else{
window.clearInterval(_3e60.timer);
_3e60.timer=-1;
}
};
if(_3e60.timer>0){
window.clearInterval(_3e60.timer);
}
_3e60.timer=window.setInterval(_3e61,30);
}
_3e5c.setCanvas(this);
if(xPos&&yPos){
_3e5c.setPosition(xPos,yPos);
}
if(_3e5c instanceof Line){
this.canvasLines.add(_3e5c);
this.html.appendChild(_3e5c.getHTMLElement());
}else{
var obj=this.canvasLines.getFirstElement();
if(obj==null){
this.html.appendChild(_3e5c.getHTMLElement());
}else{
this.html.insertBefore(_3e5c.getHTMLElement(),obj.getHTMLElement());
}
}
if(!_3e5f){
_3e5c.paint();
}
};
Canvas.prototype.removeFigure=function(_3e63){
if(this.enableSmoothFigureHandling==true){
var oThis=this;
var _3e65=_3e63;
var _3e66=function(){
if(_3e65.alpha>0){
_3e65.setAlpha(Math.max(0,_3e65.alpha-0.05));
}else{
window.clearInterval(_3e65.timer);
_3e65.timer=-1;
oThis.html.removeChild(_3e65.html);
_3e65.setCanvas(null);
}
};
if(_3e65.timer>0){
window.clearInterval(_3e65.timer);
}
_3e65.timer=window.setInterval(_3e66,20);
}else{
this.html.removeChild(_3e63.html);
_3e63.setCanvas(null);
}
if(_3e63 instanceof Line){
this.canvasLines.remove(_3e63);
}
};
Canvas.prototype.getEnableSmoothFigureHandling=function(){
return this.enableSmoothFigureHandling;
};
Canvas.prototype.setEnableSmoothFigureHandling=function(flag){
this.enableSmoothFigureHandling=flag;
};
Canvas.prototype.getWidth=function(){
return parseInt(this.html.style.width);
};
Canvas.prototype.getHeight=function(){
return parseInt(this.html.style.height);
};
Canvas.prototype.setBackgroundImage=function(_3e68,_3e69){
if(_3e68!=null){
if(_3e69){
this.html.style.background="transparent url("+_3e68+") ";
}else{
this.html.style.background="transparent url("+_3e68+") no-repeat";
}
}else{
this.html.style.background="transparent";
}
};
Canvas.prototype.getY=function(){
return this.y;
};
Canvas.prototype.getX=function(){
return this.x;
};
Canvas.prototype.getAbsoluteY=function(){
var el=this.html;
var ot=el.offsetTop;
while((el=el.offsetParent)!=null){
ot+=el.offsetTop;
}
return ot;
};
Canvas.prototype.getAbsoluteX=function(){
var el=this.html;
var ol=el.offsetLeft;
while((el=el.offsetParent)!=null){
ol+=el.offsetLeft;
}
return ol;
};
Canvas.prototype.getScrollLeft=function(){
return this.scrollArea.scrollLeft;
};
Canvas.prototype.getScrollTop=function(){
return this.scrollArea.scrollTop;
};
Workflow=function(id){
if(!id){
return;
}
this.gridWidthX=10;
this.gridWidthY=10;
this.snapToGridHelper=null;
this.verticalSnapToHelperLine=null;
this.horizontalSnapToHelperLine=null;
this.figures=new ArrayList();
this.lines=new ArrayList();
this.commonPorts=new ArrayList();
this.dropTargets=new ArrayList();
this.compartments=new ArrayList();
this.selectionListeners=new ArrayList();
this.dialogs=new ArrayList();
this.toolPalette=null;
this.dragging=false;
this.tooltip=null;
this.draggingLine=null;
this.commandStack=new CommandStack();
this.oldScrollPosLeft=0;
this.oldScrollPosTop=0;
this.currentSelection=null;
this.currentMenu=null;
this.connectionLine=new Line();
this.resizeHandleStart=new LineStartResizeHandle(this);
this.resizeHandleEnd=new LineEndResizeHandle(this);
this.resizeHandle1=new ResizeHandle(this,1);
this.resizeHandle2=new ResizeHandle(this,2);
this.resizeHandle3=new ResizeHandle(this,3);
this.resizeHandle4=new ResizeHandle(this,4);
this.resizeHandle5=new ResizeHandle(this,5);
this.resizeHandle6=new ResizeHandle(this,6);
this.resizeHandle7=new ResizeHandle(this,7);
this.resizeHandle8=new ResizeHandle(this,8);
this.resizeHandleHalfWidth=parseInt(this.resizeHandle2.getWidth()/2);
Canvas.call(this,id);
this.setPanning(false);
if(this.html!=null){
this.html.style.backgroundImage="url(grid_10.png)";
oThis=this;
this.html.tabIndex="0";
var _4116=function(){
var _4117=arguments[0]||window.event;
var diffX=_4117.clientX;
var diffY=_4117.clientY;
var _411a=oThis.getScrollLeft();
var _411b=oThis.getScrollTop();
var _411c=oThis.getAbsoluteX();
var _411d=oThis.getAbsoluteY();
if(oThis.getBestFigure(diffX+_411a-_411c,diffY+_411b-_411d)!=null){
return;
}
var line=oThis.getBestLine(diffX+_411a-_411c,diffY+_411b-_411d,null);
if(line!=null){
line.onContextMenu(diffX+_411a-_411c,diffY+_411b-_411d);
}else{
oThis.onContextMenu(diffX+_411a-_411c,diffY+_411b-_411d);
}
};
this.html.oncontextmenu=function(){
return false;
};
var oThis=this;
var _4120=function(event){
var ctrl=event.ctrlKey;
oThis.onKeyDown(event.keyCode,ctrl);
};
var _4123=function(){
var _4124=arguments[0]||window.event;
var diffX=_4124.clientX;
var diffY=_4124.clientY;
var _4127=oThis.getScrollLeft();
var _4128=oThis.getScrollTop();
var _4129=oThis.getAbsoluteX();
var _412a=oThis.getAbsoluteY();
oThis.onMouseDown(diffX+_4127-_4129,diffY+_4128-_412a);
};
var _412b=function(){
var _412c=arguments[0]||window.event;
if(oThis.currentMenu!=null){
oThis.removeFigure(oThis.currentMenu);
oThis.currentMenu=null;
}
if(_412c.button==2){
return;
}
var diffX=_412c.clientX;
var diffY=_412c.clientY;
var _412f=oThis.getScrollLeft();
var _4130=oThis.getScrollTop();
var _4131=oThis.getAbsoluteX();
var _4132=oThis.getAbsoluteY();
oThis.onMouseUp(diffX+_412f-_4131,diffY+_4130-_4132);
};
var _4133=function(){
var _4134=arguments[0]||window.event;
var diffX=_4134.clientX;
var diffY=_4134.clientY;
var _4137=oThis.getScrollLeft();
var _4138=oThis.getScrollTop();
var _4139=oThis.getAbsoluteX();
var _413a=oThis.getAbsoluteY();
oThis.currentMouseX=diffX+_4137-_4139;
oThis.currentMouseY=diffY+_4138-_413a;
var obj=oThis.getBestFigure(oThis.currentMouseX,oThis.currentMouseY);
if(Drag.currentHover!=null&&obj==null){
var _413c=new DragDropEvent();
_413c.initDragDropEvent("mouseleave",false,oThis);
Drag.currentHover.dispatchEvent(_413c);
}else{
var diffX=_4134.clientX;
var diffY=_4134.clientY;
var _4137=oThis.getScrollLeft();
var _4138=oThis.getScrollTop();
var _4139=oThis.getAbsoluteX();
var _413a=oThis.getAbsoluteY();
oThis.onMouseMove(diffX+_4137-_4139,diffY+_4138-_413a);
}
if(obj==null){
Drag.currentHover=null;
}
if(oThis.tooltip!=null){
if(Math.abs(oThis.currentTooltipX-oThis.currentMouseX)>10||Math.abs(oThis.currentTooltipY-oThis.currentMouseY)>10){
oThis.showTooltip(null);
}
}
};
var _413d=function(_413e){
var _413e=arguments[0]||window.event;
var diffX=_413e.clientX;
var diffY=_413e.clientY;
var _4141=oThis.getScrollLeft();
var _4142=oThis.getScrollTop();
var _4143=oThis.getAbsoluteX();
var _4144=oThis.getAbsoluteY();
var line=oThis.getBestLine(diffX+_4141-_4143,diffY+_4142-_4144,null);
if(line!=null){
line.onDoubleClick();
}
};
if(this.html.addEventListener){
this.html.addEventListener("contextmenu",_4116,false);
this.html.addEventListener("mousemove",_4133,false);
this.html.addEventListener("mouseup",_412b,false);
this.html.addEventListener("mousedown",_4123,false);
this.html.addEventListener("keydown",_4120,false);
this.html.addEventListener("dblclick",_413d,false);
}else{
if(this.html.attachEvent){
this.html.attachEvent("oncontextmenu",_4116);
this.html.attachEvent("onmousemove",_4133);
this.html.attachEvent("onmousedown",_4123);
this.html.attachEvent("onmouseup",_412b);
this.html.attachEvent("onkeydown",_4120);
this.html.attachEvent("ondblclick",_413d);
}else{
throw new Error("Open-jACOB Draw2D not supported in this browser.");
}
}
}
};
Workflow.prototype=new Canvas;
Workflow.prototype.type="Workflow";
Workflow.COLOR_GREEN=new Color(0,255,0);
Workflow.prototype.onScroll=function(){
var _4146=this.getScrollLeft();
var _4147=this.getScrollTop();
var _4148=_4146-this.oldScrollPosLeft;
var _4149=_4147-this.oldScrollPosTop;
for(var i=0;i<this.figures.getSize();i++){
var _414b=this.figures.get(i);
if(_414b.hasFixedPosition&&_414b.hasFixedPosition()==true){
_414b.setPosition(_414b.getX()+_4148,_414b.getY()+_4149);
}
}
this.oldScrollPosLeft=_4146;
this.oldScrollPosTop=_4147;
};
Workflow.prototype.setPanning=function(flag){
this.panning=flag;
if(flag){
this.html.style.cursor="move";
}else{
this.html.style.cursor="default";
}
};
Workflow.prototype.scrollTo=function(x,y,fast){
if(fast){
this.scrollArea.scrollLeft=x;
this.scrollArea.scrollTop=y;
}else{
var steps=40;
var xStep=(x-this.getScrollLeft())/steps;
var yStep=(y-this.getScrollTop())/steps;
var oldX=this.getScrollLeft();
var oldY=this.getScrollTop();
for(var i=0;i<steps;i++){
this.scrollArea.scrollLeft=oldX+(xStep*i);
this.scrollArea.scrollTop=oldY+(yStep*i);
}
}
};
Workflow.prototype.showTooltip=function(_4156,_4157){
if(this.tooltip!=null){
this.removeFigure(this.tooltip);
this.tooltip=null;
if(this.tooltipTimer>=0){
window.clearTimeout(this.tooltipTimer);
this.tooltipTimer=-1;
}
}
this.tooltip=_4156;
if(this.tooltip!=null){
this.currentTooltipX=this.currentMouseX;
this.currentTooltipY=this.currentMouseY;
this.addFigure(this.tooltip,this.currentTooltipX+10,this.currentTooltipY+10);
var oThis=this;
var _4159=function(){
oThis.tooltipTimer=-1;
oThis.showTooltip(null);
};
if(_4157==true){
this.tooltipTimer=window.setTimeout(_4159,5000);
}
}
};
Workflow.prototype.showDialog=function(_415a,xPos,yPos){
if(xPos){
this.addFigure(_415a,xPos,yPos);
}else{
this.addFigure(_415a,200,100);
}
this.dialogs.add(_415a);
};
Workflow.prototype.showMenu=function(menu,xPos,yPos){
if(this.menu!=null){
this.html.removeChild(this.menu.getHTMLElement());
this.menu.setWorkflow();
}
this.menu=menu;
if(this.menu!=null){
this.menu.setWorkflow(this);
this.menu.setPosition(xPos,yPos);
this.html.appendChild(this.menu.getHTMLElement());
this.menu.paint();
}
};
Workflow.prototype.onContextMenu=function(x,y){
var menu=this.getContextMenu();
if(menu!=null){
this.showMenu(menu,x,y);
}
};
Workflow.prototype.getContextMenu=function(){
return null;
};
Workflow.prototype.setToolWindow=function(_4163,x,y){
this.toolPalette=_4163;
if(y){
this.addFigure(_4163,x,y);
}else{
this.addFigure(_4163,20,20);
}
this.dialogs.add(_4163);
};
Workflow.prototype.setSnapToGrid=function(flag){
if(flag){
this.snapToGridHelper=new SnapToGrid(this);
}else{
this.snapToGridHelper=null;
}
};
Workflow.prototype.setSnapToGeometry=function(flag){
if(flag){
this.snapToGeometryHelper=new SnapToGeometry(this);
}else{
this.snapToGeometryHelper=null;
}
};
Workflow.prototype.setGridWidth=function(dx,dy){
this.gridWidthX=dx;
this.gridWidthY=dy;
};
Workflow.prototype.addFigure=function(_416a,xPos,yPos){
Canvas.prototype.addFigure.call(this,_416a,xPos,yPos,true);
_416a.setWorkflow(this);
var _416d=this;
if(_416a instanceof CompartmentFigure){
this.compartments.add(_416a);
}
if(_416a instanceof Line){
this.lines.add(_416a);
}else{
this.figures.add(_416a);
_416a.draggable.addEventListener("dragend",function(_416e){
});
_416a.draggable.addEventListener("dragstart",function(_416f){
var _4170=_416d.getFigure(_416f.target.element.id);
if(_4170==null){
return;
}
if(_4170.isSelectable()==false){
return;
}
_416d.showResizeHandles(_4170);
_416d.setCurrentSelection(_4170);
});
_416a.draggable.addEventListener("drag",function(_4171){
var _4172=_416d.getFigure(_4171.target.element.id);
if(_4172==null){
return;
}
if(_4172.isSelectable()==false){
return;
}
_416d.moveResizeHandles(_4172);
});
}
_416a.paint();
this.setDocumentDirty();
};
Workflow.prototype.removeFigure=function(_4173){
Canvas.prototype.removeFigure.call(this,_4173);
this.figures.remove(_4173);
this.lines.remove(_4173);
this.dialogs.remove(_4173);
_4173.setWorkflow(null);
if(_4173 instanceof CompartmentFigure){
this.compartments.remove(_4173);
}
if(_4173 instanceof Connection){
_4173.disconnect();
}
if(this.currentSelection==_4173){
this.setCurrentSelection(null);
}
this.setDocumentDirty();
};
Workflow.prototype.moveFront=function(_4174){
this.html.removeChild(_4174.getHTMLElement());
this.html.appendChild(_4174.getHTMLElement());
};
Workflow.prototype.moveBack=function(_4175){
this.html.removeChild(_4175.getHTMLElement());
this.html.insertBefore(_4175.getHTMLElement(),this.html.firstChild);
};
Workflow.prototype.getBestCompartmentFigure=function(x,y,_4178){
var _4179=null;
for(var i=0;i<this.figures.getSize();i++){
var _417b=this.figures.get(i);
if((_417b instanceof CompartmentFigure)&&_417b.isOver(x,y)==true&&_417b!=_4178){
if(_4179==null){
_4179=_417b;
}else{
if(_4179.getZOrder()<_417b.getZOrder()){
_4179=_417b;
}
}
}
}
return _4179;
};
Workflow.prototype.getBestFigure=function(x,y,_417e){
var _417f=null;
for(var i=0;i<this.figures.getSize();i++){
var _4181=this.figures.get(i);
if(_4181.isOver(x,y)==true&&_4181!=_417e){
if(_417f==null){
_417f=_4181;
}else{
if(_417f.getZOrder()<_4181.getZOrder()){
_417f=_4181;
}
}
}
}
return _417f;
};
Workflow.prototype.getBestLine=function(x,y,_4184){
var _4185=null;
for(var i=0;i<this.lines.getSize();i++){
var line=this.lines.get(i);
if(line.containsPoint(x,y)==true&&line!=_4184){
if(_4185==null){
_4185=line;
}else{
if(_4185.getZOrder()<line.getZOrder()){
_4185=line;
}
}
}
}
return _4185;
};
Workflow.prototype.getFigure=function(id){
for(var i=0;i<this.figures.getSize();i++){
var _418a=this.figures.get(i);
if(_418a.id==id){
return _418a;
}
}
return null;
};
Workflow.prototype.getFigures=function(){
return this.figures;
};
Workflow.prototype.getDocument=function(){
return new Document(this);
};
Workflow.prototype.addSelectionListener=function(w){
this.selectionListeners.add(w);
};
Workflow.prototype.removeSelectionListener=function(w){
this.selectionListeners.remove(w);
};
Workflow.prototype.setCurrentSelection=function(_418d){
if(_418d==null){
this.hideResizeHandles();
this.hideLineResizeHandles();
}
this.currentSelection=_418d;
for(var i=0;i<this.selectionListeners.getSize();i++){
var w=this.selectionListeners.get(i);
if(w!=null&&w.onSelectionChanged){
w.onSelectionChanged(this.currentSelection);
}
}
};
Workflow.prototype.getCurrentSelection=function(){
return this.currentSelection;
};
Workflow.prototype.getLines=function(){
return this.lines;
};
Workflow.prototype.registerPort=function(port){
port.draggable.targets=this.dropTargets;
this.commonPorts.add(port);
this.dropTargets.add(port.dropable);
};
Workflow.prototype.unregisterPort=function(port){
port.draggable.targets=null;
this.commonPorts.remove(port);
this.dropTargets.remove(port.dropable);
};
Workflow.prototype.getCommandStack=function(){
return this.commandStack;
};
Workflow.prototype.showConnectionLine=function(x1,y1,x2,y2){
this.connectionLine.setStartPoint(x1,y1);
this.connectionLine.setEndPoint(x2,y2);
if(this.connectionLine.canvas==null){
Canvas.prototype.addFigure.call(this,this.connectionLine);
}
};
Workflow.prototype.hideConnectionLine=function(){
if(this.connectionLine.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.connectionLine);
}
};
Workflow.prototype.showLineResizeHandles=function(_4196){
var _4197=this.resizeHandleStart.getWidth()/2;
var _4198=this.resizeHandleStart.getHeight()/2;
var _4199=_4196.getStartPoint();
var _419a=_4196.getEndPoint();
Canvas.prototype.addFigure.call(this,this.resizeHandleStart,_4199.x-_4197,_4199.y-_4197);
Canvas.prototype.addFigure.call(this,this.resizeHandleEnd,_419a.x-_4197,_419a.y-_4197);
this.resizeHandleStart.setCanDrag(_4196.isResizeable());
this.resizeHandleEnd.setCanDrag(_4196.isResizeable());
if(_4196.isResizeable()){
this.resizeHandleStart.setBackgroundColor(Workflow.COLOR_GREEN);
this.resizeHandleEnd.setBackgroundColor(Workflow.COLOR_GREEN);
this.resizeHandleStart.draggable.targets=this.dropTargets;
this.resizeHandleEnd.draggable.targets=this.dropTargets;
}else{
this.resizeHandleStart.setBackgroundColor(null);
this.resizeHandleEnd.setBackgroundColor(null);
}
};
Workflow.prototype.hideLineResizeHandles=function(){
if(this.resizeHandleStart.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandleStart);
}
if(this.resizeHandleEnd.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandleEnd);
}
};
Workflow.prototype.showResizeHandles=function(_419b){
this.hideLineResizeHandles();
this.hideResizeHandles();
if(this.getEnableSmoothFigureHandling()==true&&this.getCurrentSelection()!=_419b){
this.resizeHandle1.setAlpha(0.01);
this.resizeHandle2.setAlpha(0.01);
this.resizeHandle3.setAlpha(0.01);
this.resizeHandle4.setAlpha(0.01);
this.resizeHandle5.setAlpha(0.01);
this.resizeHandle6.setAlpha(0.01);
this.resizeHandle7.setAlpha(0.01);
this.resizeHandle8.setAlpha(0.01);
}
var _419c=this.resizeHandle1.getWidth();
var _419d=this.resizeHandle1.getHeight();
var _419e=_419b.getHeight();
var _419f=_419b.getWidth();
var xPos=_419b.getX();
var yPos=_419b.getY();
Canvas.prototype.addFigure.call(this,this.resizeHandle1,xPos-_419c,yPos-_419d);
Canvas.prototype.addFigure.call(this,this.resizeHandle3,xPos+_419f,yPos-_419d);
Canvas.prototype.addFigure.call(this,this.resizeHandle5,xPos+_419f,yPos+_419e);
Canvas.prototype.addFigure.call(this,this.resizeHandle7,xPos-_419c,yPos+_419e);
this.moveFront(this.resizeHandle1);
this.moveFront(this.resizeHandle3);
this.moveFront(this.resizeHandle5);
this.moveFront(this.resizeHandle7);
this.resizeHandle1.setCanDrag(_419b.isResizeable());
this.resizeHandle3.setCanDrag(_419b.isResizeable());
this.resizeHandle5.setCanDrag(_419b.isResizeable());
this.resizeHandle7.setCanDrag(_419b.isResizeable());
if(_419b.isResizeable()){
var green=new Color(0,255,0);
this.resizeHandle1.setBackgroundColor(green);
this.resizeHandle3.setBackgroundColor(green);
this.resizeHandle5.setBackgroundColor(green);
this.resizeHandle7.setBackgroundColor(green);
}else{
this.resizeHandle1.setBackgroundColor(null);
this.resizeHandle3.setBackgroundColor(null);
this.resizeHandle5.setBackgroundColor(null);
this.resizeHandle7.setBackgroundColor(null);
}
if(_419b.isStrechable()&&_419b.isResizeable()){
this.resizeHandle2.setCanDrag(_419b.isResizeable());
this.resizeHandle4.setCanDrag(_419b.isResizeable());
this.resizeHandle6.setCanDrag(_419b.isResizeable());
this.resizeHandle8.setCanDrag(_419b.isResizeable());
Canvas.prototype.addFigure.call(this,this.resizeHandle2,xPos+(_419f/2)-this.resizeHandleHalfWidth,yPos-_419d);
Canvas.prototype.addFigure.call(this,this.resizeHandle4,xPos+_419f,yPos+(_419e/2)-(_419d/2));
Canvas.prototype.addFigure.call(this,this.resizeHandle6,xPos+(_419f/2)-this.resizeHandleHalfWidth,yPos+_419e);
Canvas.prototype.addFigure.call(this,this.resizeHandle8,xPos-_419c,yPos+(_419e/2)-(_419d/2));
this.moveFront(this.resizeHandle2);
this.moveFront(this.resizeHandle4);
this.moveFront(this.resizeHandle6);
this.moveFront(this.resizeHandle8);
}
};
Workflow.prototype.hideResizeHandles=function(){
if(this.resizeHandle1.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle1);
}
if(this.resizeHandle2.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle2);
}
if(this.resizeHandle3.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle3);
}
if(this.resizeHandle4.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle4);
}
if(this.resizeHandle5.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle5);
}
if(this.resizeHandle6.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle6);
}
if(this.resizeHandle7.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle7);
}
if(this.resizeHandle8.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle8);
}
};
Workflow.prototype.moveResizeHandles=function(_41a3){
var _41a4=this.resizeHandle1.getWidth();
var _41a5=this.resizeHandle1.getHeight();
var _41a6=_41a3.getHeight();
var _41a7=_41a3.getWidth();
var xPos=_41a3.getX();
var yPos=_41a3.getY();
this.resizeHandle1.setPosition(xPos-_41a4,yPos-_41a5);
this.resizeHandle3.setPosition(xPos+_41a7,yPos-_41a5);
this.resizeHandle5.setPosition(xPos+_41a7,yPos+_41a6);
this.resizeHandle7.setPosition(xPos-_41a4,yPos+_41a6);
if(_41a3.isStrechable()){
this.resizeHandle2.setPosition(xPos+(_41a7/2)-this.resizeHandleHalfWidth,yPos-_41a5);
this.resizeHandle4.setPosition(xPos+_41a7,yPos+(_41a6/2)-(_41a5/2));
this.resizeHandle6.setPosition(xPos+(_41a7/2)-this.resizeHandleHalfWidth,yPos+_41a6);
this.resizeHandle8.setPosition(xPos-_41a4,yPos+(_41a6/2)-(_41a5/2));
}
};
Workflow.prototype.onMouseDown=function(x,y){
this.dragging=true;
this.mouseDownPosX=x;
this.mouseDownPosY=y;
if(this.toolPalette!=null&&this.toolPalette.getActiveTool()!=null){
this.toolPalette.getActiveTool().execute(x,y);
}
this.setCurrentSelection(null);
this.showMenu(null);
var size=this.getLines().getSize();
for(var i=0;i<size;i++){
var line=this.lines.get(i);
if(line.containsPoint(x,y)&&line.isSelectable()){
this.hideResizeHandles();
this.setCurrentSelection(line);
this.showLineResizeHandles(this.currentSelection);
if(line instanceof Line&&!(line instanceof Connection)){
this.draggingLine=line;
}
break;
}
}
};
Workflow.prototype.onMouseUp=function(x,y){
this.dragging=false;
this.draggingLine=null;
};
Workflow.prototype.onMouseMove=function(x,y){
if(this.dragging==true&&this.draggingLine!=null){
var diffX=x-this.mouseDownPosX;
var diffY=y-this.mouseDownPosY;
this.draggingLine.startX=this.draggingLine.getStartX()+diffX;
this.draggingLine.startY=this.draggingLine.getStartY()+diffY;
this.draggingLine.setEndPoint(this.draggingLine.getEndX()+diffX,this.draggingLine.getEndY()+diffY);
this.mouseDownPosX=x;
this.mouseDownPosY=y;
this.showLineResizeHandles(this.currentSelection);
}else{
if(this.dragging==true&&this.panning==true){
var diffX=x-this.mouseDownPosX;
var diffY=y-this.mouseDownPosY;
this.scrollTo(this.getScrollLeft()-diffX,this.getScrollTop()-diffY,true);
this.onScroll();
}
}
};
Workflow.prototype.onKeyDown=function(_41b5,ctrl){
if(_41b5==46&&this.currentSelection!=null&&this.currentSelection.isDeleteable()){
this.commandStack.execute(new CommandDelete(this.currentSelection));
}else{
if(_41b5==90&&ctrl){
this.commandStack.undo();
}else{
if(_41b5==89&&ctrl){
this.commandStack.redo();
}
}
}
};
Workflow.prototype.setDocumentDirty=function(){
for(var i=0;i<this.dialogs.getSize();i++){
var d=this.dialogs.get(i);
if(d!=null&&d.onSetDocumentDirty){
d.onSetDocumentDirty();
}
}
if(this.snapToGeometryHelper!=null){
this.snapToGeometryHelper.onSetDocumentDirty();
}
if(this.snapToGridHelper!=null){
this.snapToGridHelper.onSetDocumentDirty();
}
};
Workflow.prototype.snapToHelper=function(_41b9,pos){
if(this.snapToGeometryHelper!=null){
if(_41b9 instanceof ResizeHandle){
var _41bb=_41b9.getSnapToGridAnchor();
pos.x+=_41bb.x;
pos.y+=_41bb.y;
var _41bc=new Point(pos.x,pos.y);
var _41bd=_41b9.getSnapToDirection();
var _41be=this.snapToGeometryHelper.snapPoint(_41bd,pos,_41bc);
if((_41bd&SnapToHelper.EAST_WEST)&&!(_41be&SnapToHelper.EAST_WEST)){
this.showSnapToHelperLineVertical(_41bc.x);
}else{
this.hideSnapToHelperLineVertical();
}
if((_41bd&SnapToHelper.NORTH_SOUTH)&&!(_41be&SnapToHelper.NORTH_SOUTH)){
this.showSnapToHelperLineHorizontal(_41bc.y);
}else{
this.hideSnapToHelperLineHorizontal();
}
_41bc.x-=_41bb.x;
_41bc.y-=_41bb.y;
return _41bc;
}else{
var _41bf=new Dimension(pos.x,pos.y,_41b9.getWidth(),_41b9.getHeight());
var _41bc=new Dimension(pos.x,pos.y,_41b9.getWidth(),_41b9.getHeight());
var _41bd=SnapToHelper.NSEW;
var _41be=this.snapToGeometryHelper.snapRectangle(_41bf,_41bc);
if((_41bd&SnapToHelper.WEST)&&!(_41be&SnapToHelper.WEST)){
this.showSnapToHelperLineVertical(_41bc.x);
}else{
if((_41bd&SnapToHelper.EAST)&&!(_41be&SnapToHelper.EAST)){
this.showSnapToHelperLineVertical(_41bc.getX()+_41bc.getWidth());
}else{
this.hideSnapToHelperLineVertical();
}
}
if((_41bd&SnapToHelper.NORTH)&&!(_41be&SnapToHelper.NORTH)){
this.showSnapToHelperLineHorizontal(_41bc.y);
}else{
if((_41bd&SnapToHelper.SOUTH)&&!(_41be&SnapToHelper.SOUTH)){
this.showSnapToHelperLineHorizontal(_41bc.getY()+_41bc.getHeight());
}else{
this.hideSnapToHelperLineHorizontal();
}
}
return _41bc.getTopLeft();
}
}else{
if(this.snapToGridHelper!=null){
var _41bb=_41b9.getSnapToGridAnchor();
pos.x=pos.x+_41bb.x;
pos.y=pos.y+_41bb.y;
var _41bc=new Point(pos.x,pos.y);
this.snapToGridHelper.snapPoint(0,pos,_41bc);
_41bc.x=_41bc.x-_41bb.x;
_41bc.y=_41bc.y-_41bb.y;
return _41bc;
}
}
return pos;
};
Workflow.prototype.showSnapToHelperLineHorizontal=function(_41c0){
if(this.horizontalSnapToHelperLine==null){
this.horizontalSnapToHelperLine=new Line();
this.horizontalSnapToHelperLine.setColor(new Color(175,175,255));
this.addFigure(this.horizontalSnapToHelperLine);
}
this.horizontalSnapToHelperLine.setStartPoint(0,_41c0);
this.horizontalSnapToHelperLine.setEndPoint(this.getWidth(),_41c0);
};
Workflow.prototype.showSnapToHelperLineVertical=function(_41c1){
if(this.verticalSnapToHelperLine==null){
this.verticalSnapToHelperLine=new Line();
this.verticalSnapToHelperLine.setColor(new Color(175,175,255));
this.addFigure(this.verticalSnapToHelperLine);
}
this.verticalSnapToHelperLine.setStartPoint(_41c1,0);
this.verticalSnapToHelperLine.setEndPoint(_41c1,this.getHeight());
};
Workflow.prototype.hideSnapToHelperLines=function(){
this.hideSnapToHelperLineHorizontal();
this.hideSnapToHelperLineVertical();
};
Workflow.prototype.hideSnapToHelperLineHorizontal=function(){
if(this.horizontalSnapToHelperLine!=null){
this.removeFigure(this.horizontalSnapToHelperLine);
this.horizontalSnapToHelperLine=null;
}
};
Workflow.prototype.hideSnapToHelperLineVertical=function(){
if(this.verticalSnapToHelperLine!=null){
this.removeFigure(this.verticalSnapToHelperLine);
this.verticalSnapToHelperLine=null;
}
};
Window=function(title){
this.title=title;
this.titlebar=null;
Figure.call(this);
this.setDeleteable(false);
this.setCanSnapToHelper(false);
this.setZOrder(Window.ZOrderIndex);
};
Window.prototype=new Figure;
Window.prototype.type="Window";
Window.ZOrderIndex=50000;
Window.setZOrderBaseIndex=function(index){
Window.ZOrderBaseIndex=index;
};
Window.prototype.hasFixedPosition=function(){
return true;
};
Window.prototype.hasTitleBar=function(){
return true;
};
Window.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.margin="0px";
item.style.padding="0px";
item.style.border="1px solid black";
item.style.backgroundImage="url(/skins/ext/images/gray/shapes/window_bg.png)";
//item.style.zIndex=Window.ZOrderBaseIndex;
item.style.cursor=null;
if(this.hasTitleBar()){
this.titlebar=document.createElement("div");
this.titlebar.style.position="absolute";
this.titlebar.style.left="0px";
this.titlebar.style.top="0px";
this.titlebar.style.width=this.getWidth()+"px";
this.titlebar.style.height="15px";
this.titlebar.style.margin="0px";
this.titlebar.style.padding="0px";
this.titlebar.style.font="normal 10px verdana";
this.titlebar.style.backgroundColor="blue";
this.titlebar.style.borderBottom="2px solid gray";
this.titlebar.style.whiteSpace="nowrap";
this.titlebar.style.textAlign="center";
this.titlebar.style.backgroundImage="url(/skins/ext/images/gray/shapes/window_toolbar.png)";
this.textNode=document.createTextNode(this.title);
this.titlebar.appendChild(this.textNode);
item.appendChild(this.titlebar);
}
return item;
};
Window.prototype.setDocumentDirty=function(_3b99){
};
Window.prototype.onDragend=function(){
};
Window.prototype.onDragstart=function(x,y){
if(this.titlebar==null){
return false;
}
if(this.canDrag==true&&x<parseInt(this.titlebar.style.width)&&y<parseInt(this.titlebar.style.height)){
return true;
}
return false;
};
Window.prototype.isSelectable=function(){
return false;
};
Window.prototype.setCanDrag=function(flag){
Figure.prototype.setCanDrag.call(this,flag);
this.html.style.cursor="";
if(this.titlebar==null){
return;
}
if(flag){
this.titlebar.style.cursor="move";
}else{
this.titlebar.style.cursor="";
}
};
Window.prototype.setWorkflow=function(_3b9d){
var _3b9e=this.workflow;
Figure.prototype.setWorkflow.call(this,_3b9d);
if(_3b9e!=null){
_3b9e.removeSelectionListener(this);
}
if(this.workflow!=null){
this.workflow.addSelectionListener(this);
}
};
Window.prototype.setDimension=function(w,h){
Figure.prototype.setDimension.call(this,w,h);
if(this.titlebar!=null){
this.titlebar.style.width=this.getWidth()+"px";
}
};
Window.prototype.setTitle=function(title){
this.title=title;
};
Window.prototype.getMinWidth=function(){
return 50;
};
Window.prototype.getMinHeight=function(){
return 50;
};
Window.prototype.isResizeable=function(){
return false;
};
Window.prototype.setAlpha=function(_3ba2){
};
Window.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
this.html.style.backgroundImage="";
}
};
Window.prototype.setColor=function(color){
this.lineColor=color;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border="0px";
}
};
Window.prototype.setLineWidth=function(w){
this.lineStroke=w;
this.html.style.border=this.lineStroke+"px solid black";
};
Window.prototype.onSelectionChanged=function(_3ba6){
};
Button=function(_40ad,width,_40af){
this.x=0;
this.y=0;
this.id=this.generateUId();
this.enabled=true;
this.active=false;
this.palette=_40ad;
if(width&&_40af){
this.setDimension(width,_40af);
}else{
this.setDimension(24,24);
}
this.html=this.createHTMLElement();
};
Button.prototype.type="Button";
Button.prototype.dispose=function(){
};
Button.prototype.getImageUrl=function(){
if(this.enabled){
return this.type+".png";
}else{
return this.type+"_disabled.png";
}
};
Button.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height=this.width+"px";
item.style.width=this.height+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.outline="none";
if(this.getImageUrl()!=null){
item.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
item.style.backgroundImage="";
}
var oThis=this;
this.omousedown=function(event){
if(oThis.enabled){
oThis.setActive(true);
}
event.cancelBubble=true;
event.returnValue=false;
};
this.omouseup=function(event){
if(oThis.enabled){
oThis.setActive(false);
oThis.execute();
}
event.cancelBubble=true;
event.returnValue=false;
};
if(item.addEventListener){
item.addEventListener("mousedown",this.omousedown,false);
item.addEventListener("mouseup",this.omouseup,false);
}else{
if(item.attachEvent){
item.attachEvent("onmousedown",this.omousedown);
item.attachEvent("onmouseup",this.omouseup);
}
}
return item;
};
Button.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
Button.prototype.execute=function(){
};
Button.prototype.setTooltip=function(_40b4){
this.tooltip=_40b4;
if(this.tooltip!=null){
this.html.title=this.tooltip;
}else{
this.html.title="";
}
};
Button.prototype.setActive=function(flag){
if(!this.enabled){
return;
}
this.active=flag;
if(flag==true){
this.html.style.border="2px inset";
}else{
this.html.style.border="0px";
}
};
Button.prototype.isActive=function(){
return this.active;
};
Button.prototype.setEnabled=function(flag){
this.enabled=flag;
if(this.getImageUrl()!=null){
this.html.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
this.html.style.backgroundImage="";
}
};
Button.prototype.setDimension=function(w,h){
this.width=w;
this.height=h;
if(this.html==null){
return;
}
this.html.style.width=this.width+"px";
this.html.style.height=this.height+"px";
};
Button.prototype.setPosition=function(xPos,yPos){
this.x=Math.max(0,xPos);
this.y=Math.max(0,yPos);
if(this.html==null){
return;
}
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
};
Button.prototype.getWidth=function(){
return this.width;
};
Button.prototype.getHeight=function(){
return this.height;
};
Button.prototype.getY=function(){
return this.y;
};
Button.prototype.getX=function(){
return this.x;
};
Button.prototype.getPosition=function(){
return new Point(this.x,this.y);
};
Button.prototype.getToolPalette=function(){
return this.palette;
};
Button.prototype.generateUId=function(){
var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var _40bc=10;
var _40bd=10;
nbTry=0;
while(nbTry<1000){
var id="";
for(var i=0;i<_40bc;i++){
var rnum=Math.floor(Math.random()*chars.length);
id+=chars.substring(rnum,rnum+1);
}
elem=document.getElementById(id);
if(!elem){
return id;
}
nbTry+=1;
}
return null;
};
ToggleButton=function(_3e78){
Button.call(this,_3e78);
this.isDownFlag=false;
};
ToggleButton.prototype=new Button;
ToggleButton.prototype.type="ToggleButton";
ToggleButton.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height="24px";
item.style.width="24px";
item.style.margin="0px";
item.style.padding="0px";
if(this.getImageUrl()!=null){
item.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
item.style.backgroundImage="";
}
var oThis=this;
this.omousedown=function(event){
if(oThis.enabled){
if(!oThis.isDown()){
Button.prototype.setActive.call(oThis,true);
}
}
event.cancelBubble=true;
event.returnValue=false;
};
this.omouseup=function(event){
if(oThis.enabled){
if(oThis.isDown()){
Button.prototype.setActive.call(oThis,false);
}
oThis.isDownFlag=!oThis.isDownFlag;
oThis.execute();
}
event.cancelBubble=true;
event.returnValue=false;
};
if(item.addEventListener){
item.addEventListener("mousedown",this.omousedown,false);
item.addEventListener("mouseup",this.omouseup,false);
}else{
if(item.attachEvent){
item.attachEvent("onmousedown",this.omousedown);
item.attachEvent("onmouseup",this.omouseup);
}
}
return item;
};
ToggleButton.prototype.isDown=function(){
return this.isDownFlag;
};
ToggleButton.prototype.setActive=function(flag){
Button.prototype.setActive.call(this,flag);
this.isDownFlag=flag;
};
ToggleButton.prototype.execute=function(){
};
ToolGeneric=function(_39ec){
this.x=0;
this.y=0;
this.enabled=true;
this.tooltip=null;
this.palette=_39ec;
this.setDimension(10,10);
this.html=this.createHTMLElement();
};
ToolGeneric.prototype.type="ToolGeneric";
ToolGeneric.prototype.dispose=function(){
};
ToolGeneric.prototype.getImageUrl=function(){
if(this.enabled){
return this.type+".png";
}else{
return this.type+"_disabled.png";
}
};
ToolGeneric.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height="24px";
item.style.width="24px";
item.style.margin="0px";
item.style.padding="0px";
if(this.getImageUrl()!=null){
item.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
item.style.backgroundImage="";
}
var oThis=this;
this.click=function(event){
if(oThis.enabled){
oThis.palette.setActiveTool(oThis);
}
event.cancelBubble=true;
event.returnValue=false;
};
if(item.addEventListener){
item.addEventListener("click",this.click,false);
}else{
if(item.attachEvent){
item.attachEvent("onclick",this.click);
}
}
return item;
};
ToolGeneric.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
ToolGeneric.prototype.execute=function(x,y){
if(this.enabled){
this.palette.setActiveTool(null);
}
};
ToolGeneric.prototype.setTooltip=function(_39f2){
this.tooltip=_39f2;
if(this.tooltip!=null){
this.html.title=this.tooltip;
}else{
this.html.title="";
}
};
ToolGeneric.prototype.setActive=function(flag){
if(!this.enabled){
return;
}
if(flag==true){
this.html.style.border="2px inset";
}else{
this.html.style.border="0px";
}
};
ToolGeneric.prototype.setEnabled=function(flag){
this.enabled=flag;
if(this.getImageUrl()!=null){
this.html.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
this.html.style.backgroundImage="";
}
};
ToolGeneric.prototype.setDimension=function(w,h){
this.width=w;
this.height=h;
if(this.html==null){
return;
}
this.html.style.width=this.width+"px";
this.html.style.height=this.height+"px";
};
ToolGeneric.prototype.setPosition=function(xPos,yPos){
this.x=Math.max(0,xPos);
this.y=Math.max(0,yPos);
if(this.html==null){
return;
}
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
};
ToolGeneric.prototype.getWidth=function(){
return this.width;
};
ToolGeneric.prototype.getHeight=function(){
return this.height;
};
ToolGeneric.prototype.getY=function(){
return this.y;
};
ToolGeneric.prototype.getX=function(){
return this.x;
};
ToolGeneric.prototype.getPosition=function(){
return new Point(this.x,this.y);
};
ToolPalette=function(title){
Window.call(this,title);
this.setDimension(75,400);
this.activeTool=null;
this.children=new Object();
};
ToolPalette.prototype=new Window;
ToolPalette.prototype.type="ToolPalette";
ToolPalette.prototype.dispose=function(){
Window.prototype.dispose.call(this);
};
ToolPalette.prototype.createHTMLElement=function(){
var item=Window.prototype.createHTMLElement.call(this);
this.scrollarea=document.createElement("div");
this.scrollarea.style.position="absolute";
this.scrollarea.style.left="0px";
if(this.hasTitleBar()){
this.scrollarea.style.top="15px";
}else{
this.scrollarea.style.top="0px";
}
this.scrollarea.style.width=this.getWidth()+"px";
this.scrollarea.style.height="15px";
this.scrollarea.style.margin="0px";
this.scrollarea.style.padding="0px";
this.scrollarea.style.font="normal 10px verdana";
this.scrollarea.style.borderBottom="2px solid gray";
this.scrollarea.style.whiteSpace="nowrap";
this.scrollarea.style.textAlign="center";
this.scrollarea.style.overflowX="auto";
this.scrollarea.style.overflowY="auto";
this.scrollarea.style.overflow="auto";
item.appendChild(this.scrollarea);
return item;
};
ToolPalette.prototype.setDimension=function(w,h){
Window.prototype.setDimension.call(this,w,h);
if(this.scrollarea!=null){
this.scrollarea.style.width=this.getWidth()+"px";
if(this.hasTitleBar()){
this.scrollarea.style.height=(this.getHeight()-15)+"px";
}else{
this.scrollarea.style.height=this.getHeight()+"px";
}
}
};
ToolPalette.prototype.addChild=function(item){
this.children[item.id]=item;
this.scrollarea.appendChild(item.getHTMLElement());
};
ToolPalette.prototype.getChild=function(id){
return this.children[id];
};
ToolPalette.prototype.getActiveTool=function(){
return this.activeTool;
};
ToolPalette.prototype.setActiveTool=function(tool){
if(this.activeTool!=tool&&this.activeTool!=null){
this.activeTool.setActive(false);
}
if(tool!=null){
tool.setActive(true);
}
this.activeTool=tool;
};
Dialog=function(title){
this.buttonbar=null;
if(title){
Window.call(this,title);
}else{
Window.call(this,"Dialog");
}
this.setDimension(400,300);
};
Dialog.prototype=new Window;
Dialog.prototype.type="Dialog";
Dialog.prototype.createHTMLElement=function(){
var item=Window.prototype.createHTMLElement.call(this);
var oThis=this;
this.buttonbar=document.createElement("div");
this.buttonbar.style.position="absolute";
this.buttonbar.style.left="0px";
this.buttonbar.style.bottom="0px";
this.buttonbar.style.width=this.getWidth()+"px";
this.buttonbar.style.height="30px";
this.buttonbar.style.margin="0px";
this.buttonbar.style.padding="0px";
this.buttonbar.style.font="normal 10px verdana";
this.buttonbar.style.backgroundColor="#C0C0C0";
this.buttonbar.style.borderBottom="2px solid gray";
this.buttonbar.style.whiteSpace="nowrap";
this.buttonbar.style.textAlign="center";
this.okbutton=document.createElement("button");
this.okbutton.style.border="1px solid gray";
this.okbutton.style.font="normal 10px verdana";
this.okbutton.style.width="80px";
this.okbutton.style.margin="5px";
this.okbutton.innerHTML="Ok";
this.okbutton.onclick=function(){
oThis.onOk();
};
this.buttonbar.appendChild(this.okbutton);
this.cancelbutton=document.createElement("button");
this.cancelbutton.innerHTML="Cancel";
this.cancelbutton.style.font="normal 10px verdana";
this.cancelbutton.style.border="1px solid gray";
this.cancelbutton.style.width="80px";
this.cancelbutton.style.margin="5px";
this.cancelbutton.onclick=function(){
oThis.onCancel();
};
this.buttonbar.appendChild(this.cancelbutton);
item.appendChild(this.buttonbar);
return item;
};
Dialog.prototype.onOk=function(){
this.workflow.removeFigure(this);
};
Dialog.prototype.onCancel=function(){
this.workflow.removeFigure(this);
};
Dialog.prototype.setDimension=function(w,h){
Window.prototype.setDimension.call(this,w,h);
if(this.buttonbar!=null){
this.buttonbar.style.width=this.getWidth()+"px";
}
};
Dialog.prototype.setWorkflow=function(_31c1){
Window.prototype.setWorkflow.call(this,_31c1);
this.setFocus();
};
Dialog.prototype.setFocus=function(){
};
Dialog.prototype.onSetDocumentDirty=function(){
};
InputDialog=function(){
Dialog.call(this);
this.setDimension(400,100);
};
InputDialog.prototype=new Dialog;
InputDialog.prototype.type="InputDialog";
InputDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
return item;
};
InputDialog.prototype.onOk=function(){
this.workflow.removeFigure(this);
};
InputDialog.prototype.onCancel=function(){
this.workflow.removeFigure(this);
};
PropertyDialog=function(_3f50,_3f51,label){
this.figure=_3f50;
this.propertyName=_3f51;
this.label=label;
Dialog.call(this);
this.setDimension(400,120);
};
PropertyDialog.prototype=new Dialog;
PropertyDialog.prototype.type="PropertyDialog";
PropertyDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
var _3f54=document.createElement("form");
_3f54.style.position="absolute";
_3f54.style.left="10px";
_3f54.style.top="30px";
_3f54.style.width="375px";
_3f54.style.font="normal 10px verdana";
item.appendChild(_3f54);
this.labelDiv=document.createElement("div");
this.labelDiv.innerHTML=this.label;
this.disableTextSelection(this.labelDiv);
_3f54.appendChild(this.labelDiv);
this.input=document.createElement("input");
this.input.style.border="1px solid gray";
this.input.style.font="normal 10px verdana";
this.input.type="text";
var value=this.figure.getProperty(this.propertyName);
if(value){
this.input.value=value;
}else{
this.input.value="";
}
this.input.style.width="100%";
_3f54.appendChild(this.input);
this.input.focus();
return item;
};
PropertyDialog.prototype.onOk=function(){
Dialog.prototype.onOk.call(this);
this.figure.setProperty(this.propertyName,this.input.value);
};
AnnotationDialog=function(_2e5e){
this.figure=_2e5e;
Dialog.call(this);
this.setDimension(400,100);
};
AnnotationDialog.prototype=new Dialog;
AnnotationDialog.prototype.type="AnnotationDialog";
AnnotationDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
var _2e60=document.createElement("form");
_2e60.style.position="absolute";
_2e60.style.left="10px";
_2e60.style.top="30px";
_2e60.style.width="375px";
_2e60.style.font="normal 10px verdana";
item.appendChild(_2e60);
this.label=document.createTextNode("Text");
_2e60.appendChild(this.label);
this.input=document.createElement("input");
this.input.style.border="1px solid gray";
this.input.style.font="normal 10px verdana";
this.input.type="text";
var value=this.figure.getText();
if(value){
this.input.value=value;
}else{
this.input.value="";
}
this.input.style.width="100%";
_2e60.appendChild(this.input);
this.input.focus();
return item;
};
AnnotationDialog.prototype.onOk=function(){
this.workflow.getCommandStack().execute(new CommandSetText(this.figure,this.input.value));
this.workflow.removeFigure(this);
};
PropertyWindow=function(){
this.currentSelection=null;
Window.call(this,"Property Window");
this.setDimension(200,100);
};
PropertyWindow.prototype=new Window;
PropertyWindow.prototype.type="PropertyWindow";
PropertyWindow.prototype.dispose=function(){
Window.prototype.dispose.call(this);
};
PropertyWindow.prototype.createHTMLElement=function(){
var item=Window.prototype.createHTMLElement.call(this);
item.appendChild(this.createLabel("Type:",15,25));
item.appendChild(this.createLabel("X :",15,50));
item.appendChild(this.createLabel("Y :",15,70));
item.appendChild(this.createLabel("Width :",85,50));
item.appendChild(this.createLabel("Height :",85,70));
this.labelType=this.createLabel("",50,25);
this.labelX=this.createLabel("",40,50);
this.labelY=this.createLabel("",40,70);
this.labelWidth=this.createLabel("",135,50);
this.labelHeight=this.createLabel("",135,70);
this.labelType.style.fontWeight="normal";
this.labelX.style.fontWeight="normal";
this.labelY.style.fontWeight="normal";
this.labelWidth.style.fontWeight="normal";
this.labelHeight.style.fontWeight="normal";
item.appendChild(this.labelType);
item.appendChild(this.labelX);
item.appendChild(this.labelY);
item.appendChild(this.labelWidth);
item.appendChild(this.labelHeight);
return item;
};
PropertyWindow.prototype.onSelectionChanged=function(_31cf){
Window.prototype.onSelectionChanged.call(this,_31cf);
if(this.currentSelection!=null){
this.currentSelection.detachMoveListener(this);
}
this.currentSelection=_31cf;
if(_31cf!=null&&_31cf!=this){
this.labelType.innerHTML=_31cf.type;
if(_31cf.getX){
this.labelX.innerHTML=_31cf.getX();
this.labelY.innerHTML=_31cf.getY();
this.labelWidth.innerHTML=_31cf.getWidth();
this.labelHeight.innerHTML=_31cf.getHeight();
this.currentSelection=_31cf;
this.currentSelection.attachMoveListener(this);
}else{
this.labelX.innerHTML="";
this.labelY.innerHTML="";
this.labelWidth.innerHTML="";
this.labelHeight.innerHTML="";
}
}else{
this.labelType.innerHTML="<none>";
this.labelX.innerHTML="";
this.labelY.innerHTML="";
this.labelWidth.innerHTML="";
this.labelHeight.innerHTML="";
}
};
PropertyWindow.prototype.getCurrentSelection=function(){
return this.currentSelection;
};
PropertyWindow.prototype.onOtherFigureMoved=function(_31d0){
if(_31d0==this.currentSelection){
this.onSelectionChanged(_31d0);
}
};
PropertyWindow.prototype.createLabel=function(text,x,y){
var l=document.createElement("div");
l.style.position="absolute";
l.style.left=x+"px";
l.style.top=y+"px";
l.style.font="normal 10px verdana";
l.style.whiteSpace="nowrap";
l.style.fontWeight="bold";
l.innerHTML=text;
return l;
};
ColorDialog=function(){
this.maxValue={"h":"359","s":"100","v":"100"};
this.HSV={0:359,1:100,2:100};
this.slideHSV={0:359,1:100,2:100};
this.SVHeight=165;
this.wSV=162;
this.wH=162;
Dialog.call(this,"Color Chooser");
this.loadSV();
this.setColor(new Color(255,0,0));
this.setDimension(219,244);
};
ColorDialog.prototype=new Dialog;
ColorDialog.prototype.type="ColorDialog";
ColorDialog.prototype.createHTMLElement=function(){
var oThis=this;
var item=Dialog.prototype.createHTMLElement.call(this);
this.outerDiv=document.createElement("div");
this.outerDiv.id="plugin";
this.outerDiv.style.top="15px";
this.outerDiv.style.left="0px";
this.outerDiv.style.width="201px";
this.outerDiv.style.position="absolute";
this.outerDiv.style.padding="9px";
this.outerDiv.display="block";
this.outerDiv.style.background="#0d0d0d";
this.plugHEX=document.createElement("div");
this.plugHEX.id="plugHEX";
this.plugHEX.innerHTML="F1FFCC";
this.plugHEX.style.color="white";
this.plugHEX.style.font="normal 10px verdana";
this.outerDiv.appendChild(this.plugHEX);
this.SV=document.createElement("div");
this.SV.onmousedown=function(event){
oThis.mouseDownSV(oThis.SVslide,event);
};
this.SV.id="SV";
this.SV.style.cursor="crosshair";
this.SV.style.background="#FF0000 url(SatVal.png)";
this.SV.style.position="absolute";
this.SV.style.height="166px";
this.SV.style.width="167px";
this.SV.style.marginRight="10px";
this.SV.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='SatVal.png', sizingMethod='scale')";
this.SV.style["float"]="left";
this.outerDiv.appendChild(this.SV);
this.SVslide=document.createElement("div");
this.SVslide.onmousedown=function(event){
oThis.mouseDownSV(event);
};
this.SVslide.style.top="40px";
this.SVslide.style.left="40px";
this.SVslide.style.position="absolute";
this.SVslide.style.cursor="crosshair";
this.SVslide.style.background="url(slide.gif)";
this.SVslide.style.height="9px";
this.SVslide.style.width="9px";
this.SVslide.style.lineHeight="1px";
this.outerDiv.appendChild(this.SVslide);
this.H=document.createElement("form");
this.H.id="H";
this.H.onmousedown=function(event){
oThis.mouseDownH(event);
};
this.H.style.border="1px solid #000000";
this.H.style.cursor="crosshair";
this.H.style.position="absolute";
this.H.style.width="19px";
this.H.style.top="28px";
this.H.style.left="191px";
this.outerDiv.appendChild(this.H);
this.Hslide=document.createElement("div");
this.Hslide.style.top="-7px";
this.Hslide.style.left="-8px";
this.Hslide.style.background="url(slideHue.gif)";
this.Hslide.style.height="5px";
this.Hslide.style.width="33px";
this.Hslide.style.position="absolute";
this.Hslide.style.lineHeight="1px";
this.H.appendChild(this.Hslide);
this.Hmodel=document.createElement("div");
this.Hmodel.style.height="1px";
this.Hmodel.style.width="19px";
this.Hmodel.style.lineHeight="1px";
this.Hmodel.style.margin="0px";
this.Hmodel.style.padding="0px";
this.Hmodel.style.fontSize="1px";
this.H.appendChild(this.Hmodel);
item.appendChild(this.outerDiv);
return item;
};
ColorDialog.prototype.onOk=function(){
Dialog.prototype.onOk.call(this);
};
browser=function(v){
return (Math.max(navigator.userAgent.toLowerCase().indexOf(v),0));
};
ColorDialog.prototype.showColor=function(c){
this.plugHEX.style.background="#"+c;
this.plugHEX.innerHTML=c;
};
ColorDialog.prototype.getSelectedColor=function(){
var rgb=this.hex2rgb(this.plugHEX.innerHTML);
return new Color(rgb[0],rgb[1],rgb[2]);
};
ColorDialog.prototype.setColor=function(color){
if(color==null){
color=new Color(100,100,100);
}
var hex=this.rgb2hex(Array(color.getRed(),color.getGreen(),color.getBlue()));
this.updateH(hex);
};
ColorDialog.prototype.XY=function(e,v){
var z=browser("msie")?Array(event.clientX+document.body.scrollLeft,event.clientY+document.body.scrollTop):Array(e.pageX,e.pageY);
return z[v];
};
ColorDialog.prototype.mkHSV=function(a,b,c){
return (Math.min(a,Math.max(0,Math.ceil((parseInt(c)/b)*a))));
};
ColorDialog.prototype.ckHSV=function(a,b){
if(a>=0&&a<=b){
return (a);
}else{
if(a>b){
return (b);
}else{
if(a<0){
return ("-"+oo);
}
}
}
};
ColorDialog.prototype.mouseDownH=function(e){
this.slideHSV[0]=this.HSV[0];
var oThis=this;
this.H.onmousemove=function(e){
oThis.dragH(e);
};
this.H.onmouseup=function(e){
oThis.H.onmousemove="";
oThis.H.onmouseup="";
};
this.dragH(e);
};
ColorDialog.prototype.dragH=function(e){
var y=this.XY(e,1)-this.getY()-40;
this.Hslide.style.top=(this.ckHSV(y,this.wH)-5)+"px";
this.slideHSV[0]=this.mkHSV(359,this.wH,this.Hslide.style.top);
this.updateSV();
this.showColor(this.commit());
this.SV.style.backgroundColor="#"+this.hsv2hex(Array(this.HSV[0],100,100));
};
ColorDialog.prototype.mouseDownSV=function(o,e){
this.slideHSV[0]=this.HSV[0];
var oThis=this;
function reset(){
oThis.SV.onmousemove="";
oThis.SV.onmouseup="";
oThis.SVslide.onmousemove="";
oThis.SVslide.onmouseup="";
}
this.SV.onmousemove=function(e){
oThis.dragSV(e);
};
this.SV.onmouseup=reset;
this.SVslide.onmousemove=function(e){
oThis.dragSV(e);
};
this.SVslide.onmouseup=reset;
this.dragSV(e);
};
ColorDialog.prototype.dragSV=function(e){
var x=this.XY(e,0)-this.getX()-1;
var y=this.XY(e,1)-this.getY()-20;
this.SVslide.style.left=this.ckHSV(x,this.wSV)+"px";
this.SVslide.style.top=this.ckHSV(y,this.wSV)+"px";
this.slideHSV[1]=this.mkHSV(100,this.wSV,this.SVslide.style.left);
this.slideHSV[2]=100-this.mkHSV(100,this.wSV,this.SVslide.style.top);
this.updateSV();
};
ColorDialog.prototype.commit=function(){
var r="hsv";
var z={};
var j="";
for(var i=0;i<=r.length-1;i++){
j=r.substr(i,1);
z[i]=(j=="h")?this.maxValue[j]-this.mkHSV(this.maxValue[j],this.wH,this.Hslide.style.top):this.HSV[i];
}
return (this.updateSV(this.hsv2hex(z)));
};
ColorDialog.prototype.updateSV=function(v){
this.HSV=v?this.hex2hsv(v):Array(this.slideHSV[0],this.slideHSV[1],this.slideHSV[2]);
if(!v){
v=this.hsv2hex(Array(this.slideHSV[0],this.slideHSV[1],this.slideHSV[2]));
}
this.showColor(v);
return v;
};
ColorDialog.prototype.loadSV=function(){
var z="";
for(var i=this.SVHeight;i>=0;i--){
z+="<div style=\"background:#"+this.hsv2hex(Array(Math.round((359/this.SVHeight)*i),100,100))+";\"><br/></div>";
}
this.Hmodel.innerHTML=z;
};
ColorDialog.prototype.updateH=function(v){
this.plugHEX.innerHTML=v;
this.HSV=this.hex2hsv(v);
this.SV.style.backgroundColor="#"+this.hsv2hex(Array(this.HSV[0],100,100));
this.SVslide.style.top=(parseInt(this.wSV-this.wSV*(this.HSV[1]/100))+20)+"px";
this.SVslide.style.left=(parseInt(this.wSV*(this.HSV[1]/100))+5)+"px";
this.Hslide.style.top=(parseInt(this.wH*((this.maxValue["h"]-this.HSV[0])/this.maxValue["h"]))-7)+"px";
};
ColorDialog.prototype.toHex=function(v){
v=Math.round(Math.min(Math.max(0,v),255));
return ("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16));
};
ColorDialog.prototype.hex2rgb=function(r){
return ({0:parseInt(r.substr(0,2),16),1:parseInt(r.substr(2,2),16),2:parseInt(r.substr(4,2),16)});
};
ColorDialog.prototype.rgb2hex=function(r){
return (this.toHex(r[0])+this.toHex(r[1])+this.toHex(r[2]));
};
ColorDialog.prototype.hsv2hex=function(h){
return (this.rgb2hex(this.hsv2rgb(h)));
};
ColorDialog.prototype.hex2hsv=function(v){
return (this.rgb2hsv(this.hex2rgb(v)));
};
ColorDialog.prototype.rgb2hsv=function(r){
var max=Math.max(r[0],r[1],r[2]);
var delta=max-Math.min(r[0],r[1],r[2]);
var H;
var S;
var V;
if(max!=0){
S=Math.round(delta/max*100);
if(r[0]==max){
H=(r[1]-r[2])/delta;
}else{
if(r[1]==max){
H=2+(r[2]-r[0])/delta;
}else{
if(r[2]==max){
H=4+(r[0]-r[1])/delta;
}
}
}
var H=Math.min(Math.round(H*60),360);
if(H<0){
H+=360;
}
}
return ({0:H?H:0,1:S?S:0,2:Math.round((max/255)*100)});
};
ColorDialog.prototype.hsv2rgb=function(r){
var R;
var B;
var G;
var S=r[1]/100;
var V=r[2]/100;
var H=r[0]/360;
if(S>0){
if(H>=1){
H=0;
}
H=6*H;
F=H-Math.floor(H);
A=Math.round(255*V*(1-S));
B=Math.round(255*V*(1-(S*F)));
C=Math.round(255*V*(1-(S*(1-F))));
V=Math.round(255*V);
switch(Math.floor(H)){
case 0:
R=V;
G=C;
B=A;
break;
case 1:
R=B;
G=V;
B=A;
break;
case 2:
R=A;
G=V;
B=C;
break;
case 3:
R=A;
G=B;
B=V;
break;
case 4:
R=C;
G=A;
B=V;
break;
case 5:
R=V;
G=A;
B=B;
break;
}
return ({0:R?R:0,1:G?G:0,2:B?B:0});
}else{
return ({0:(V=Math.round(V*255)),1:V,2:V});
}
};
LineColorDialog=function(_2e57){
ColorDialog.call(this);
this.figure=_2e57;
var color=_2e57.getColor();
this.updateH(this.rgb2hex(color.getRed(),color.getGreen(),color.getBlue()));
};
LineColorDialog.prototype=new ColorDialog;
LineColorDialog.prototype.type="LineColorDialog";
LineColorDialog.prototype.onOk=function(){
var _2e59=this.workflow;
ColorDialog.prototype.onOk.call(this);
if(typeof this.figure.setColor=="function"){
_2e59.getCommandStack().execute(new CommandSetColor(this.figure,this.getSelectedColor()));
if(_2e59.getCurrentSelection()==this.figure){
_2e59.setCurrentSelection(this.figure);
}
}
};
BackgroundColorDialog=function(_40a6){
ColorDialog.call(this);
this.figure=_40a6;
var color=_40a6.getBackgroundColor();
if(color!=null){
this.updateH(this.rgb2hex(color.getRed(),color.getGreen(),color.getBlue()));
}
};
BackgroundColorDialog.prototype=new ColorDialog;
BackgroundColorDialog.prototype.type="BackgroundColorDialog";
BackgroundColorDialog.prototype.onOk=function(){
var _40a8=this.workflow;
ColorDialog.prototype.onOk.call(this);
if(typeof this.figure.setBackgroundColor=="function"){
_40a8.getCommandStack().execute(new CommandSetBackgroundColor(this.figure,this.getSelectedColor()));
if(_40a8.getCurrentSelection()==this.figure){
_40a8.setCurrentSelection(this.figure);
}
}
};
AnnotationDialog=function(_2e5e){
this.figure=_2e5e;
Dialog.call(this);
this.setDimension(400,100);
};
AnnotationDialog.prototype=new Dialog;
AnnotationDialog.prototype.type="AnnotationDialog";
AnnotationDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
var _2e60=document.createElement("form");
_2e60.style.position="absolute";
_2e60.style.left="10px";
_2e60.style.top="30px";
_2e60.style.width="375px";
_2e60.style.font="normal 10px verdana";
item.appendChild(_2e60);
this.label=document.createTextNode("Text");
_2e60.appendChild(this.label);
this.input=document.createElement("input");
this.input.style.border="1px solid gray";
this.input.style.font="normal 10px verdana";
this.input.type="text";
var value=this.figure.getText();
if(value){
this.input.value=value;
}else{
this.input.value="";
}
this.input.style.width="100%";
_2e60.appendChild(this.input);
this.input.focus();
return item;
};
AnnotationDialog.prototype.onOk=function(){
this.workflow.getCommandStack().execute(new CommandSetText(this.figure,this.input.value));
this.workflow.removeFigure(this);
};
Command=function(label){
this.label=label;
};
Command.prototype.type="Command";
Command.prototype.getLabel=function(){
};
Command.prototype.canExecute=function(){
return true;
};
Command.prototype.execute=function(){
};
Command.prototype.undo=function(){
};
Command.prototype.redo=function(){
};
CommandStack=function(){
this.undostack=new Array();
this.redostack=new Array();
this.maxundo=50;
this.eventListeners=new ArrayList();
};
CommandStack.PRE_EXECUTE=1;
CommandStack.PRE_REDO=2;
CommandStack.PRE_UNDO=4;
CommandStack.POST_EXECUTE=8;
CommandStack.POST_REDO=16;
CommandStack.POST_UNDO=32;
CommandStack.POST_MASK=CommandStack.POST_EXECUTE|CommandStack.POST_UNDO|CommandStack.POST_REDO;
CommandStack.PRE_MASK=CommandStack.PRE_EXECUTE|CommandStack.PRE_UNDO|CommandStack.PRE_REDO;
CommandStack.prototype.type="CommandStack";
CommandStack.prototype.setUndoLimit=function(count){
this.maxundo=count;
};
CommandStack.prototype.markSaveLocation=function(){
this.undostack=new Array();
this.redostack=new Array();
};
CommandStack.prototype.execute=function(_3f6c){
if(_3f6c.canExecute()==false){
return;
}
this.notifyListeners(_3f6c,CommandStack.PRE_EXECUTE);
this.undostack.push(_3f6c);
_3f6c.execute();
this.redostack=new Array();
if(this.undostack.length>this.maxundo){
this.undostack=this.undostack.slice(this.undostack.length-this.maxundo);
}
this.notifyListeners(_3f6c,CommandStack.POST_EXECUTE);
};
CommandStack.prototype.undo=function(){
var _3f6d=this.undostack.pop();
if(_3f6d){
this.notifyListeners(_3f6d,CommandStack.PRE_UNDO);
this.redostack.push(_3f6d);
_3f6d.undo();
this.notifyListeners(_3f6d,CommandStack.POST_UNDO);
}
};
CommandStack.prototype.redo=function(){
var _3f6e=this.redostack.pop();
if(_3f6e){
this.notifyListeners(_3f6e,CommandStack.PRE_REDO);
this.undostack.push(_3f6e);
_3f6e.redo();
this.notifyListeners(_3f6e,CommandStack.POST_REDO);
}
};
CommandStack.prototype.canRedo=function(){
return this.redostack.length>0;
};
CommandStack.prototype.canUndo=function(){
return this.undostack.length>0;
};
CommandStack.prototype.addCommandStackEventListener=function(_3f6f){
this.eventListeners.add(_3f6f);
};
CommandStack.prototype.removeCommandStackEventListener=function(_3f70){
this.eventListeners.remove(_3f70);
};
CommandStack.prototype.notifyListeners=function(_3f71,state){
var event=new CommandStackEvent(_3f71,state);
var size=this.eventListeners.getSize();
for(var i=0;i<size;i++){
this.eventListeners.get(i).stackChanged(event);
}
};
CommandStackEvent=function(_3e48,_3e49){
this.command=_3e48;
this.details=_3e49;
};
CommandStackEvent.prototype.type="CommandStackEvent";
CommandStackEvent.prototype.getCommand=function(){
return this.command;
};
CommandStackEvent.prototype.getDetails=function(){
return this.details;
};
CommandStackEvent.prototype.isPostChangeEvent=function(){
return 0!=(this.getDetails()&CommandStack.POST_MASK);
};
CommandStackEvent.prototype.isPreChangeEvent=function(){
return 0!=(this.getDetails()&CommandStack.PRE_MASK);
};
CommandStackEventListener=function(){
};
CommandStackEventListener.prototype.type="CommandStackEventListener";
CommandStackEventListener.prototype.stackChanged=function(event){
};
CommandAdd=function(_4089,_408a,x,y,_408d){
Command.call(this,"add figure");
this.parent=_408d;
this.figure=_408a;
this.x=x;
this.y=y;
this.workflow=_4089;
};
CommandAdd.prototype=new Command;
CommandAdd.prototype.type="CommandAdd";
CommandAdd.prototype.execute=function(){
this.redo();
};
CommandAdd.prototype.redo=function(){
if(this.x&&this.y){
this.workflow.addFigure(this.figure,this.x,this.y);
}else{
this.workflow.addFigure(this.figure);
}
this.workflow.setCurrentSelection(this.figure);
if(this.parent!=null){
this.parent.addChild(this.figure);
}
};
CommandAdd.prototype.undo=function(){
this.workflow.removeFigure(this.figure);
this.workflow.setCurrentSelection(null);
if(this.parent!=null){
this.parent.removeChild(this.figure);
}
};
CommandDelete=function(_3f13){
Command.call(this,"delete figure");
this.parent=_3f13.parent;
this.figure=_3f13;
this.workflow=_3f13.workflow;
this.connections=null;
};
CommandDelete.prototype=new Command;
CommandDelete.prototype.type="CommandDelete";
CommandDelete.prototype.execute=function(){
this.redo();
};
CommandDelete.prototype.undo=function(){
this.workflow.addFigure(this.figure);
if(this.figure instanceof Connection){
this.figure.reconnect();
}
this.workflow.setCurrentSelection(this.figure);
if(this.parent!=null){
this.parent.addChild(this.figure);
}
for(var i=0;i<this.connections.getSize();++i){
this.workflow.addFigure(this.connections.get(i));
this.connections.get(i).reconnect();
}
};
CommandDelete.prototype.redo=function(){
this.workflow.removeFigure(this.figure);
this.workflow.setCurrentSelection(null);
if(this.figure.getPorts&&this.connections==null){
this.connections=new ArrayList();
var ports=this.figure.getPorts();
for(var i=0;i<ports.getSize();i++){
if(ports.get(i).getConnections){
this.connections.addAll(ports.get(i).getConnections());
}
}
}
if(this.connections==null){
this.connections=new ArrayList();
}
if(this.parent!=null){
this.parent.removeChild(this.figure);
}
for(var i=0;i<this.connections.getSize();++i){
this.workflow.removeFigure(this.connections.get(i));
}
};
CommandMove=function(_3f21,x,y){
Command.call(this,"move figure");
this.figure=_3f21;
this.oldX=x;
this.oldY=y;
this.oldCompartment=_3f21.getParent();
};
CommandMove.prototype=new Command;
CommandMove.prototype.type="CommandMove";
CommandMove.prototype.setPosition=function(x,y){
this.newX=x;
this.newY=y;
this.newCompartment=this.figure.workflow.getBestCompartmentFigure(x,y,this.figure);
};
CommandMove.prototype.canExecute=function(){
return this.newX!=this.oldX||this.newY!=this.oldY;
};
CommandMove.prototype.execute=function(){
this.redo();
};
CommandMove.prototype.undo=function(){
this.figure.setPosition(this.oldX,this.oldY);
if(this.newCompartment!=null){
this.newCompartment.removeChild(this.figure);
}
if(this.oldCompartment!=null){
this.oldCompartment.addChild(this.figure);
}
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandMove.prototype.redo=function(){
this.figure.setPosition(this.newX,this.newY);
if(this.oldCompartment!=null){
this.oldCompartment.removeChild(this.figure);
}
if(this.newCompartment!=null){
this.newCompartment.addChild(this.figure);
}
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandResize=function(_3e82,width,_3e84){
Command.call(this,"resize figure");
this.figure=_3e82;
this.oldWidth=width;
this.oldHeight=_3e84;
};
CommandResize.prototype=new Command;
CommandResize.prototype.type="CommandResize";
CommandResize.prototype.setDimension=function(width,_3e86){
this.newWidth=width;
this.newHeight=_3e86;
};
CommandResize.prototype.canExecute=function(){
return this.newWidth!=this.oldWidth||this.newHeight!=this.oldHeight;
};
CommandResize.prototype.execute=function(){
this.redo();
};
CommandResize.prototype.undo=function(){
this.figure.setDimension(this.oldWidth,this.oldHeight);
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandResize.prototype.redo=function(){
this.figure.setDimension(this.newWidth,this.newHeight);
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandSetText=function(_41ee,text){
Command.call(this,"set text");
this.figure=_41ee;
this.newText=text;
this.oldText=_41ee.getText();
};
CommandSetText.prototype=new Command;
CommandSetText.prototype.type="CommandSetText";
CommandSetText.prototype.execute=function(){
this.redo();
};
CommandSetText.prototype.redo=function(){
this.figure.setText(this.newText);
};
CommandSetText.prototype.undo=function(){
this.figure.setText(this.oldText);
};
CommandSetColor=function(_3a42,color){
Command.call(this,"set color");
this.figure=_3a42;
this.newColor=color;
this.oldColor=_3a42.getColor();
};
CommandSetColor.prototype=new Command;
CommandSetColor.prototype.type="CommandSetColor";
CommandSetColor.prototype.execute=function(){
this.redo();
};
CommandSetColor.prototype.undo=function(){
this.figure.setColor(this.oldColor);
};
CommandSetColor.prototype.redo=function(){
this.figure.setColor(this.newColor);
};
CommandSetBackgroundColor=function(_2d19,color){
Command.call(this,"set background color");
this.figure=_2d19;
this.newColor=color;
this.oldColor=_2d19.getBackgroundColor();
};
CommandSetBackgroundColor.prototype=new Command;
CommandSetBackgroundColor.prototype.type="CommandSetBackgroundColor";
CommandSetBackgroundColor.prototype.execute=function(){
this.redo();
};
CommandSetBackgroundColor.prototype.undo=function(){
this.figure.setBackgroundColor(this.oldColor);
};
CommandSetBackgroundColor.prototype.redo=function(){
this.figure.setBackgroundColor(this.newColor);
};
CommandConnect=function(_4063,_4064,_4065){
Command.call(this,"create connection");
this.workflow=_4063;
this.source=_4064;
this.target=_4065;
this.connection=null;
};
CommandConnect.prototype=new Command;
CommandConnect.prototype.type="CommandConnect";
CommandConnect.prototype.setConnection=function(_4066){
this.connection=_4066;
};
CommandConnect.prototype.execute=function(){
if(this.connection==null){
this.connection=new Connection();
}
this.connection.setSource(this.source);
this.connection.setTarget(this.target);
this.workflow.addFigure(this.connection);
};
CommandConnect.prototype.redo=function(){
this.workflow.addFigure(this.connection);
this.connection.reconnect();
};
CommandConnect.prototype.undo=function(){
this.workflow.removeFigure(this.connection);
};
CommandReconnect=function(con){
Command.call(this,"reconnect connection");
this.con=con;
this.oldSourcePort=con.getSource();
this.oldTargetPort=con.getTarget();
this.oldRouter=con.getRouter();
};
CommandReconnect.prototype=new Command;
CommandReconnect.prototype.type="CommandReconnect";
CommandReconnect.prototype.canExecute=function(){
return true;
};
CommandReconnect.prototype.setNewPorts=function(_3548,_3549){
this.newSourcePort=_3548;
this.newTargetPort=_3549;
};
CommandReconnect.prototype.execute=function(){
this.redo();
};
CommandReconnect.prototype.undo=function(){
this.con.setSource(this.oldSourcePort);
this.con.setTarget(this.oldTargetPort);
this.con.setRouter(this.oldRouter);
if(this.con.getWorkflow().getCurrentSelection()==this.con){
this.con.getWorkflow().showLineResizeHandles(this.con);
}
};
CommandReconnect.prototype.redo=function(){
this.con.setSource(this.newSourcePort);
this.con.setTarget(this.newTargetPort);
this.con.setRouter(this.oldRouter);
if(this.con.getWorkflow().getCurrentSelection()==this.con){
this.con.getWorkflow().showLineResizeHandles(this.con);
}
};
CommandMoveLine=function(line,_359c,_359d,endX,endY){
Command.call(this,"move line");
this.line=line;
this.startX1=_359c;
this.startY1=_359d;
this.endX1=endX;
this.endY1=endY;
};
CommandMoveLine.prototype=new Command;
CommandMoveLine.prototype.type="CommandMoveLine";
CommandMoveLine.prototype.canExecute=function(){
return this.startX1!=this.startX2||this.startY1!=this.startY2||this.endX1!=this.endX2||this.endY1!=this.endY2;
};
CommandMoveLine.prototype.setEndPoints=function(_35a0,_35a1,endX,endY){
this.startX2=_35a0;
this.startY2=_35a1;
this.endX2=endX;
this.endY2=endY;
};
CommandMoveLine.prototype.execute=function(){
this.redo();
};
CommandMoveLine.prototype.undo=function(){
this.line.setStartPoint(this.startX1,this.startY1);
this.line.setEndPoint(this.endX1,this.endY1);
if(this.line.workflow.getCurrentSelection()==this.line){
this.line.workflow.showLineResizeHandles(this.line);
}
};
CommandMoveLine.prototype.redo=function(){
this.line.setStartPoint(this.startX2,this.startY2);
this.line.setEndPoint(this.endX2,this.endY2);
if(this.line.workflow.getCurrentSelection()==this.line){
this.line.workflow.showLineResizeHandles(this.line);
}
};
Menu=function(){
this.menuItems=new ArrayList();
Figure.call(this);
this.setSelectable(false);
this.setDeleteable(false);
this.setCanDrag(false);
this.setResizeable(false);
this.setSelectable(false);
this.setZOrder(10000);
this.dirty=false;
};
Menu.prototype=new Figure;
Menu.prototype.type="Menu";
Menu.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.zIndex=""+Figure.ZOrderBaseIndex;
item.style.border="1px solid gray";
item.style.background="lavender";
item.style.cursor="pointer";
return item;
};
Menu.prototype.setWorkflow=function(_41f4){
this.workflow=_41f4;
};
Menu.prototype.appendMenuItem=function(item){
this.menuItems.add(item);
item.parentMenu=this;
this.dirty=true;
};
Menu.prototype.getHTMLElement=function(){
var html=Figure.prototype.getHTMLElement.call(this);
if(this.dirty){
this.createList();
}
return html;
};
Menu.prototype.createList=function(){
this.dirty=false;
this.html.innerHTML="";
var oThis=this;
for(var i=0;i<this.menuItems.getSize();i++){
var item=this.menuItems.get(i);
var li=document.createElement("a");
li.innerHTML=item.getLabel();
li.style.display="block";
li.style.fontFamily="Verdana, Arial, Helvetica, sans-serif";
li.style.fontSize="9pt";
li.style.color="dimgray";
li.style.borderBottom="1px solid silver";
li.style.paddingLeft="5px";
li.style.paddingRight="5px";
li.style.cursor="pointer";
this.html.appendChild(li);
li.menuItem=item;
if(li.addEventListener){
li.addEventListener("click",function(event){
var _41fc=arguments[0]||window.event;
_41fc.cancelBubble=true;
_41fc.returnValue=false;
var diffX=_41fc.clientX;
var diffY=_41fc.clientY;
var _41ff=document.body.parentNode.scrollLeft;
var _4200=document.body.parentNode.scrollTop;
this.menuItem.execute(diffX+_41ff,diffY+_4200);
},false);
li.addEventListener("mouseup",function(event){
event.cancelBubble=true;
event.returnValue=false;
},false);
li.addEventListener("mousedown",function(event){
event.cancelBubble=true;
event.returnValue=false;
},false);
li.addEventListener("mouseover",function(event){
this.style.backgroundColor="silver";
},false);
li.addEventListener("mouseout",function(event){
this.style.backgroundColor="transparent";
},false);
}else{
if(li.attachEvent){
li.attachEvent("onclick",function(event){
var _4206=arguments[0]||window.event;
_4206.cancelBubble=true;
_4206.returnValue=false;
var diffX=_4206.clientX;
var diffY=_4206.clientY;
var _4209=document.body.parentNode.scrollLeft;
var _420a=document.body.parentNode.scrollTop;
event.srcElement.menuItem.execute(diffX+_4209,diffY+_420a);
});
li.attachEvent("onmousedown",function(event){
event.cancelBubble=true;
event.returnValue=false;
});
li.attachEvent("onmouseup",function(event){
event.cancelBubble=true;
event.returnValue=false;
});
li.attachEvent("onmouseover",function(event){
event.srcElement.style.backgroundColor="silver";
});
li.attachEvent("onmouseout",function(event){
event.srcElement.style.backgroundColor="transparent";
});
}
}
}
};
MenuItem=function(label,_3f5b,_3f5c){
this.label=label;
this.iconUrl=_3f5b;
this.parentMenu=null;
this.action=_3f5c;
};
MenuItem.prototype.type="MenuItem";
MenuItem.prototype.isEnabled=function(){
return true;
};
MenuItem.prototype.getLabel=function(){
return this.label;
};
MenuItem.prototype.execute=function(x,y){
this.parentMenu.workflow.showMenu(null);
this.action(x,y);
};
Locator=function(){
};
Locator.prototype.type="Locator";
Locator.prototype.relocate=function(_3a8d){
};
ConnectionLocator=function(_3f69){
Locator.call(this);
this.connection=_3f69;
};
ConnectionLocator.prototype=new Locator;
ConnectionLocator.prototype.type="ConnectionLocator";
ConnectionLocator.prototype.getConnection=function(){
return this.connection;
};
ManhattenMidpointLocator=function(_3b8e){
ConnectionLocator.call(this,_3b8e);
};
ManhattenMidpointLocator.prototype=new ConnectionLocator;
ManhattenMidpointLocator.prototype.type="ManhattenMidpointLocator";
ManhattenMidpointLocator.prototype.relocate=function(_3b8f){
var conn=this.getConnection();
var p=new Point();
var _3b92=conn.getPoints();
var index=Math.floor((_3b92.getSize()-2)/2);
var p1=_3b92.get(index);
var p2=_3b92.get(index+1);
p.x=(p2.x-p1.x)/2+p1.x+5;
p.y=(p2.y-p1.y)/2+p1.y+5;
_3b8f.setPosition(p.x,p.y);
};
|
gulliver/js/ext/draw2d.js
|
/**This notice must be untouched at all times.
This is the COMPRESSED version of the Draw2D Library
WebSite: http://www.draw2d.org
Copyright: 2006 Andreas Herz. All rights reserved.
Created: 5.11.2006 by Andreas Herz (Web: http://www.freegroup.de )
LICENSE: LGPL
**/
Event=function(){
this.type=null;
this.target=null;
this.relatedTarget=null;
this.cancelable=false;
this.timeStamp=null;
this.returnValue=true;
};
Event.prototype.initEvent=function(sType,_3a0c){
this.type=sType;
this.cancelable=_3a0c;
this.timeStamp=(new Date()).getTime();
};
Event.prototype.preventDefault=function(){
if(this.cancelable){
this.returnValue=false;
}
};
Event.fireDOMEvent=function(_3a0d,_3a0e){
if(document.createEvent){
var evt=document.createEvent("Events");
evt.initEvent(_3a0d,true,true);
_3a0e.dispatchEvent(evt);
}else{
if(document.createEventObject){
var evt=document.createEventObject();
_3a0e.fireEvent("on"+_3a0d,evt);
}
}
};
EventTarget=function(){
this.eventhandlers=new Object();
};
EventTarget.prototype.addEventListener=function(sType,_3a11){
if(typeof this.eventhandlers[sType]=="undefined"){
this.eventhandlers[sType]=new Array;
}
this.eventhandlers[sType][this.eventhandlers[sType].length]=_3a11;
};
EventTarget.prototype.dispatchEvent=function(_3a12){
_3a12.target=this;
if(typeof this.eventhandlers[_3a12.type]!="undefined"){
for(var i=0;i<this.eventhandlers[_3a12.type].length;i++){
this.eventhandlers[_3a12.type][i](_3a12);
}
}
return _3a12.returnValue;
};
EventTarget.prototype.removeEventListener=function(sType,_3a15){
if(typeof this.eventhandlers[sType]!="undefined"){
var _3a16=new Array;
for(var i=0;i<this.eventhandlers[sType].length;i++){
if(this.eventhandlers[sType][i]!=_3a15){
_3a16[_3a16.length]=this.eventhandlers[sType][i];
}
}
this.eventhandlers[sType]=_3a16;
}
};
ArrayList=function(){
this.increment=10;
this.size=0;
this.data=new Array(this.increment);
};
ArrayList.EMPTY_LIST=new ArrayList();
ArrayList.prototype.reverse=function(){
var _3dc7=new Array(this.size);
for(var i=0;i<this.size;i++){
_3dc7[i]=this.data[this.size-i-1];
}
this.data=_3dc7;
};
ArrayList.prototype.getCapacity=function(){
return this.data.length;
};
ArrayList.prototype.getSize=function(){
return this.size;
};
ArrayList.prototype.isEmpty=function(){
return this.getSize()==0;
};
ArrayList.prototype.getLastElement=function(){
if(this.data[this.getSize()-1]!=null){
return this.data[this.getSize()-1];
}
};
ArrayList.prototype.getFirstElement=function(){
if(this.data[0]!=null){
return this.data[0];
}
};
ArrayList.prototype.get=function(i){
return this.data[i];
};
ArrayList.prototype.add=function(obj){
if(this.getSize()==this.data.length){
this.resize();
}
this.data[this.size++]=obj;
};
ArrayList.prototype.addAll=function(obj){
for(var i=0;i<obj.getSize();i++){
this.add(obj.get(i));
}
};
ArrayList.prototype.remove=function(obj){
var index=this.indexOf(obj);
if(index>=0){
return this.removeElementAt(index);
}
return null;
};
ArrayList.prototype.insertElementAt=function(obj,index){
if(this.size==this.capacity){
this.resize();
}
for(var i=this.getSize();i>index;i--){
this.data[i]=this.data[i-1];
}
this.data[index]=obj;
this.size++;
};
ArrayList.prototype.removeElementAt=function(index){
var _3dd3=this.data[index];
for(var i=index;i<(this.getSize()-1);i++){
this.data[i]=this.data[i+1];
}
this.data[this.getSize()-1]=null;
this.size--;
return _3dd3;
};
ArrayList.prototype.removeAllElements=function(){
this.size=0;
for(var i=0;i<this.data.length;i++){
this.data[i]=null;
}
};
ArrayList.prototype.indexOf=function(obj){
for(var i=0;i<this.getSize();i++){
if(this.data[i]==obj){
return i;
}
}
return -1;
};
ArrayList.prototype.contains=function(obj){
for(var i=0;i<this.getSize();i++){
if(this.data[i]==obj){
return true;
}
}
return false;
};
ArrayList.prototype.resize=function(){
newData=new Array(this.data.length+this.increment);
for(var i=0;i<this.data.length;i++){
newData[i]=this.data[i];
}
this.data=newData;
};
ArrayList.prototype.trimToSize=function(){
var temp=new Array(this.getSize());
for(var i=0;i<this.getSize();i++){
temp[i]=this.data[i];
}
this.size=temp.length-1;
this.data=temp;
};
ArrayList.prototype.sort=function(f){
var i,j;
var _3ddf;
var _3de0;
var _3de1;
var _3de2;
for(i=1;i<this.getSize();i++){
_3de0=this.data[i];
_3ddf=_3de0[f];
j=i-1;
_3de1=this.data[j];
_3de2=_3de1[f];
while(j>=0&&_3de2>_3ddf){
this.data[j+1]=this.data[j];
j--;
if(j>=0){
_3de1=this.data[j];
_3de2=_3de1[f];
}
}
this.data[j+1]=_3de0;
}
};
ArrayList.prototype.clone=function(){
var _3de3=new ArrayList(this.size);
for(var i=0;i<this.size;i++){
_3de3.add(this.data[i]);
}
return _3de3;
};
ArrayList.prototype.overwriteElementAt=function(obj,index){
this.data[index]=obj;
};
function trace(_3dbe){
var _3dbf=openwindow("about:blank",700,400);
_3dbf.document.writeln("<pre>"+_3dbe+"</pre>");
}
function openwindow(url,width,_3dc2){
var left=(screen.width-width)/2;
var top=(screen.height-_3dc2)/2;
property="left="+left+", top="+top+", toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,alwaysRaised,width="+width+",height="+_3dc2;
return window.open(url,"_blank",property);
}
function dumpObject(obj){
trace("----------------------------------------------------------------------------");
trace("- Object dump");
trace("----------------------------------------------------------------------------");
for(var i in obj){
try{
if(typeof obj[i]!="function"){
trace(i+" --> "+obj[i]);
}
}
catch(e){
}
}
for(var i in obj){
try{
if(typeof obj[i]=="function"){
trace(i+" --> "+obj[i]);
}
}
catch(e){
}
}
trace("----------------------------------------------------------------------------");
}
Drag=function(){
};
Drag.current=null;
Drag.currentTarget=null;
Drag.dragging=false;
Drag.isDragging=function(){
return this.dragging;
};
Drag.setCurrent=function(_326a){
this.current=_326a;
this.dragging=true;
};
Drag.getCurrent=function(){
return this.current;
};
Drag.clearCurrent=function(){
this.current=null;
this.dragging=false;
};
Draggable=function(_326b,_326c){
EventTarget.call(this);
this.construct(_326b,_326c);
this.diffX=0;
this.diffY=0;
this.targets=new ArrayList();
};
Draggable.prototype=new EventTarget;
Draggable.prototype.construct=function(_326d,_326e){
this.element=_326d;
this.constraints=_326e;
var oThis=this;
var _3270=function(){
var _3271=new DragDropEvent();
_3271.initDragDropEvent("dblclick",true);
oThis.dispatchEvent(_3271);
var _3272=arguments[0]||window.event;
_3272.cancelBubble=true;
_3272.returnValue=false;
};
var _3273=function(){
var _3274=arguments[0]||window.event;
var _3275=new DragDropEvent();
var _3276=oThis.node.workflow.getAbsoluteX();
var _3277=oThis.node.workflow.getAbsoluteY();
var _3278=oThis.node.workflow.getScrollLeft();
var _3279=oThis.node.workflow.getScrollTop();
_3275.x=_3274.clientX-oThis.element.offsetLeft+_3278-_3276;
_3275.y=_3274.clientY-oThis.element.offsetTop+_3279-_3277;
if(_3274.button==2){
_3275.initDragDropEvent("contextmenu",true);
oThis.dispatchEvent(_3275);
}else{
_3275.initDragDropEvent("dragstart",true);
if(oThis.dispatchEvent(_3275)){
oThis.diffX=_3274.clientX-oThis.element.offsetLeft;
oThis.diffY=_3274.clientY-oThis.element.offsetTop;
Drag.setCurrent(oThis);
if(oThis.isAttached==true){
oThis.detachEventHandlers();
}
oThis.attachEventHandlers();
}
}
_3274.cancelBubble=true;
_3274.returnValue=false;
};
var _327a=function(){
if(Drag.getCurrent()==null){
var _327b=arguments[0]||window.event;
if(Drag.currentHover!=null&&oThis!=Drag.currentHover){
var _327c=new DragDropEvent();
_327c.initDragDropEvent("mouseleave",false,oThis);
Drag.currentHover.dispatchEvent(_327c);
}
if(oThis!=null&&oThis!=Drag.currentHover){
var _327c=new DragDropEvent();
_327c.initDragDropEvent("mouseenter",false,oThis);
oThis.dispatchEvent(_327c);
}
Drag.currentHover=oThis;
}else{
}
};
if(this.element.addEventListener){
this.element.addEventListener("mousemove",_327a,false);
this.element.addEventListener("mousedown",_3273,false);
this.element.addEventListener("dblclick",_3270,false);
}else{
if(this.element.attachEvent){
this.element.attachEvent("onmousemove",_327a);
this.element.attachEvent("onmousedown",_3273);
this.element.attachEvent("ondblclick",_3270);
}else{
throw new Error("Drag not supported in this browser.");
}
}
};
Draggable.prototype.attachEventHandlers=function(){
var oThis=this;
oThis.isAttached=true;
this.tempMouseMove=function(){
var _327e=arguments[0]||window.event;
var _327f=new Point(_327e.clientX-oThis.diffX,_327e.clientY-oThis.diffY);
if(oThis.node.getCanSnapToHelper()){
_327f=oThis.node.getWorkflow().snapToHelper(oThis.node,_327f);
}
oThis.element.style.left=_327f.x+"px";
oThis.element.style.top=_327f.y+"px";
var _3280=oThis.node.workflow.getScrollLeft();
var _3281=oThis.node.workflow.getScrollTop();
var _3282=oThis.node.workflow.getAbsoluteX();
var _3283=oThis.node.workflow.getAbsoluteY();
var _3284=oThis.getDropTarget(_327e.clientX+_3280-_3282,_327e.clientY+_3281-_3283);
var _3285=oThis.getCompartment(_327e.clientX+_3280-_3282,_327e.clientY+_3281-_3283);
if(Drag.currentTarget!=null&&_3284!=Drag.currentTarget){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("dragleave",false,oThis);
Drag.currentTarget.dispatchEvent(_3286);
}
if(_3284!=null&&_3284!=Drag.currentTarget){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("dragenter",false,oThis);
_3284.dispatchEvent(_3286);
}
Drag.currentTarget=_3284;
if(Drag.currentCompartment!=null&&_3285!=Drag.currentCompartment){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("figureleave",false,oThis);
Drag.currentCompartment.dispatchEvent(_3286);
}
if(_3285!=null&&_3285.node!=oThis.node&&_3285!=Drag.currentCompartment){
var _3286=new DragDropEvent();
_3286.initDragDropEvent("figureenter",false,oThis);
_3285.dispatchEvent(_3286);
}
Drag.currentCompartment=_3285;
var _3287=new DragDropEvent();
_3287.initDragDropEvent("drag",false);
oThis.dispatchEvent(_3287);
};
oThis.tempMouseUp=function(){
oThis.detachEventHandlers();
var _3288=arguments[0]||window.event;
var _3289=new DragDropEvent();
_3289.initDragDropEvent("dragend",false);
oThis.dispatchEvent(_3289);
var _328a=oThis.node.workflow.getScrollLeft();
var _328b=oThis.node.workflow.getScrollTop();
var _328c=oThis.node.workflow.getAbsoluteX();
var _328d=oThis.node.workflow.getAbsoluteY();
var _328e=oThis.getDropTarget(_3288.clientX+_328a-_328c,_3288.clientY+_328b-_328d);
var _328f=oThis.getCompartment(_3288.clientX+_328a-_328c,_3288.clientY+_328b-_328d);
if(_328e!=null){
var _3290=new DragDropEvent();
_3290.initDragDropEvent("drop",false,oThis);
_328e.dispatchEvent(_3290);
}
if(_328f!=null&&_328f.node!=oThis.node){
var _3290=new DragDropEvent();
_3290.initDragDropEvent("figuredrop",false,oThis);
_328f.dispatchEvent(_3290);
}
if(Drag.currentTarget!=null){
var _3290=new DragDropEvent();
_3290.initDragDropEvent("dragleave",false,oThis);
Drag.currentTarget.dispatchEvent(_3290);
Drag.currentTarget=null;
}
Drag.currentCompartment=null;
Drag.clearCurrent();
};
if(document.body.addEventListener){
document.body.addEventListener("mousemove",this.tempMouseMove,false);
document.body.addEventListener("mouseup",this.tempMouseUp,false);
}else{
if(document.body.attachEvent){
document.body.attachEvent("onmousemove",this.tempMouseMove);
document.body.attachEvent("onmouseup",this.tempMouseUp);
}else{
throw new Error("Drag doesn't support this browser.");
}
}
};
Draggable.prototype.detachEventHandlers=function(){
this.isAttached=false;
if(document.body.removeEventListener){
document.body.removeEventListener("mousemove",this.tempMouseMove,false);
document.body.removeEventListener("mouseup",this.tempMouseUp,false);
}else{
if(document.body.detachEvent){
document.body.detachEvent("onmousemove",this.tempMouseMove);
document.body.detachEvent("onmouseup",this.tempMouseUp);
}else{
throw new Error("Drag doesn't support this browser.");
}
}
};
Draggable.prototype.getDropTarget=function(x,y){
for(var i=0;i<this.targets.getSize();i++){
var _3294=this.targets.get(i);
if(_3294.node.isOver(x,y)&&_3294.node!=this.node){
return _3294;
}
}
return null;
};
Draggable.prototype.getCompartment=function(x,y){
var _3297=null;
for(var i=0;i<this.node.workflow.compartments.getSize();i++){
var _3299=this.node.workflow.compartments.get(i);
if(_3299.isOver(x,y)&&_3299!=this.node){
if(_3297==null){
_3297=_3299;
}else{
if(_3297.getZOrder()<_3299.getZOrder()){
_3297=_3299;
}
}
}
}
return _3297==null?null:_3297.dropable;
};
Draggable.prototype.getLeft=function(){
return this.element.offsetLeft;
};
Draggable.prototype.getTop=function(){
return this.element.offsetTop;
};
DragDropEvent=function(){
Event.call(this);
};
DragDropEvent.prototype=new Event();
DragDropEvent.prototype.initDragDropEvent=function(sType,_329b,_329c){
this.initEvent(sType,_329b);
this.relatedTarget=_329c;
};
DropTarget=function(_329d){
EventTarget.call(this);
this.construct(_329d);
};
DropTarget.prototype=new EventTarget;
DropTarget.prototype.construct=function(_329e){
this.element=_329e;
};
DropTarget.prototype.getLeft=function(){
var el=this.element;
var ol=el.offsetLeft;
while((el=el.offsetParent)!=null){
ol+=el.offsetLeft;
}
return ol;
};
DropTarget.prototype.getTop=function(){
var el=this.element;
var ot=el.offsetTop;
while((el=el.offsetParent)!=null){
ot+=el.offsetTop;
}
return ot;
};
DropTarget.prototype.getHeight=function(){
return this.element.offsetHeight;
};
DropTarget.prototype.getWidth=function(){
return this.element.offsetWidth;
};
PositionConstants=function(){
};
PositionConstants.NORTH=1;
PositionConstants.SOUTH=4;
PositionConstants.WEST=8;
PositionConstants.EAST=16;
Color=function(red,green,blue){
if(typeof green=="undefined"){
var rgb=this.hex2rgb(red);
this.red=rgb[0];
this.green=rgb[1];
this.blue=rgb[2];
}else{
this.red=red;
this.green=green;
this.blue=blue;
}
};
Color.prototype.type="Color";
Color.prototype.getHTMLStyle=function(){
return "rgb("+this.red+","+this.green+","+this.blue+")";
};
Color.prototype.getRed=function(){
return this.red;
};
Color.prototype.getGreen=function(){
return this.green;
};
Color.prototype.getBlue=function(){
return this.blue;
};
Color.prototype.getIdealTextColor=function(){
var _3f07=105;
var _3f08=(this.red*0.299)+(this.green*0.587)+(this.blue*0.114);
return (255-_3f08<_3f07)?new Color(0,0,0):new Color(255,255,255);
};
Color.prototype.hex2rgb=function(_3f09){
_3f09=_3f09.replace("#","");
return ({0:parseInt(_3f09.substr(0,2),16),1:parseInt(_3f09.substr(2,2),16),2:parseInt(_3f09.substr(4,2),16)});
};
Color.prototype.hex=function(){
return (this.int2hex(this.red)+this.int2hex(this.green)+this.int2hex(this.blue));
};
Color.prototype.int2hex=function(v){
v=Math.round(Math.min(Math.max(0,v),255));
return ("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16));
};
Color.prototype.darker=function(_3f0b){
var red=parseInt(Math.round(this.getRed()*(1-_3f0b)));
var green=parseInt(Math.round(this.getGreen()*(1-_3f0b)));
var blue=parseInt(Math.round(this.getBlue()*(1-_3f0b)));
if(red<0){
red=0;
}else{
if(red>255){
red=255;
}
}
if(green<0){
green=0;
}else{
if(green>255){
green=255;
}
}
if(blue<0){
blue=0;
}else{
if(blue>255){
blue=255;
}
}
return new Color(red,green,blue);
};
Color.prototype.lighter=function(_3f0f){
var red=parseInt(Math.round(this.getRed()*(1+_3f0f)));
var green=parseInt(Math.round(this.getGreen()*(1+_3f0f)));
var blue=parseInt(Math.round(this.getBlue()*(1+_3f0f)));
if(red<0){
red=0;
}else{
if(red>255){
red=255;
}
}
if(green<0){
green=0;
}else{
if(green>255){
green=255;
}
}
if(blue<0){
blue=0;
}else{
if(blue>255){
blue=255;
}
}
return new Color(red,green,blue);
};
Point=function(x,y){
this.x=x;
this.y=y;
};
Point.prototype.type="Point";
Point.prototype.getX=function(){
return this.x;
};
Point.prototype.getY=function(){
return this.y;
};
Point.prototype.getPosition=function(p){
var dx=p.x-this.x;
var dy=p.y-this.y;
if(Math.abs(dx)>Math.abs(dy)){
if(dx<0){
return PositionConstants.WEST;
}
return PositionConstants.EAST;
}
if(dy<0){
return PositionConstants.NORTH;
}
return PositionConstants.SOUTH;
};
Point.prototype.equals=function(o){
return this.x==o.x&&this.y==o.y;
};
Point.prototype.getDistance=function(other){
return Math.sqrt((this.x-other.x)*(this.x-other.x)+(this.y-other.y)*(this.y-other.y));
};
Point.prototype.getTranslated=function(other){
return new Point(this.x+other.x,this.y+other.y);
};
Dimension=function(x,y,w,h){
Point.call(this,x,y);
this.w=w;
this.h=h;
};
Dimension.prototype=new Point;
Dimension.prototype.type="Dimension";
Dimension.prototype.translate=function(dx,dy){
this.x+=dx;
this.y+=dy;
return this;
};
Dimension.prototype.resize=function(dw,dh){
this.w+=dw;
this.h+=dh;
return this;
};
Dimension.prototype.setBounds=function(rect){
this.x=rect.x;
this.y=rect.y;
this.w=rect.w;
this.h=rect.h;
return this;
};
Dimension.prototype.isEmpty=function(){
return this.w<=0||this.h<=0;
};
Dimension.prototype.getWidth=function(){
return this.w;
};
Dimension.prototype.getHeight=function(){
return this.h;
};
Dimension.prototype.getRight=function(){
return this.x+this.w;
};
Dimension.prototype.getBottom=function(){
return this.y+this.h;
};
Dimension.prototype.getTopLeft=function(){
return new Point(this.x,this.y);
};
Dimension.prototype.getCenter=function(){
return new Point(this.x+this.w/2,this.y+this.h/2);
};
Dimension.prototype.getBottomRight=function(){
return new Point(this.x+this.w,this.y+this.h);
};
Dimension.prototype.equals=function(o){
return this.x==o.x&&this.y==o.y&&this.w==o.w&&this.h==o.h;
};
SnapToHelper=function(_3f1b){
this.workflow=_3f1b;
};
SnapToHelper.NORTH=1;
SnapToHelper.SOUTH=4;
SnapToHelper.WEST=8;
SnapToHelper.EAST=16;
SnapToHelper.NORTH_EAST=SnapToHelper.NORTH|SnapToHelper.EAST;
SnapToHelper.NORTH_WEST=SnapToHelper.NORTH|SnapToHelper.WEST;
SnapToHelper.SOUTH_EAST=SnapToHelper.SOUTH|SnapToHelper.EAST;
SnapToHelper.SOUTH_WEST=SnapToHelper.SOUTH|SnapToHelper.WEST;
SnapToHelper.NORTH_SOUTH=SnapToHelper.NORTH|SnapToHelper.SOUTH;
SnapToHelper.EAST_WEST=SnapToHelper.EAST|SnapToHelper.WEST;
SnapToHelper.NSEW=SnapToHelper.NORTH_SOUTH|SnapToHelper.EAST_WEST;
SnapToHelper.prototype.snapPoint=function(_3f1c,_3f1d,_3f1e){
return _3f1d;
};
SnapToHelper.prototype.snapRectangle=function(_3f1f,_3f20){
return _3f1f;
};
SnapToHelper.prototype.onSetDocumentDirty=function(){
};
SnapToGrid=function(_39d9){
SnapToHelper.call(this,_39d9);
};
SnapToGrid.prototype=new SnapToHelper;
SnapToGrid.prototype.snapPoint=function(_39da,_39db,_39dc){
_39dc.x=this.workflow.gridWidthX*Math.floor(((_39db.x+this.workflow.gridWidthX/2)/this.workflow.gridWidthX));
_39dc.y=this.workflow.gridWidthY*Math.floor(((_39db.y+this.workflow.gridWidthY/2)/this.workflow.gridWidthY));
return 0;
};
SnapToGrid.prototype.snapRectangle=function(_39dd,_39de){
_39de.x=_39dd.x;
_39de.y=_39dd.y;
_39de.w=_39dd.w;
_39de.h=_39dd.h;
return 0;
};
SnapToGeometryEntry=function(type,_39cd){
this.type=type;
this.location=_39cd;
};
SnapToGeometryEntry.prototype.getLocation=function(){
return this.location;
};
SnapToGeometryEntry.prototype.getType=function(){
return this.type;
};
SnapToGeometry=function(_40db){
SnapToHelper.call(this,_40db);
};
SnapToGeometry.prototype=new SnapToHelper;
SnapToGeometry.THRESHOLD=5;
SnapToGeometry.prototype.snapPoint=function(_40dc,_40dd,_40de){
if(this.rows==null||this.cols==null){
this.populateRowsAndCols();
}
if((_40dc&SnapToHelper.EAST)!=0){
var _40df=this.getCorrectionFor(this.cols,_40dd.getX()-1,1);
if(_40df!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.EAST;
_40de.x+=_40df;
}
}
if((_40dc&SnapToHelper.WEST)!=0){
var _40e0=this.getCorrectionFor(this.cols,_40dd.getX(),-1);
if(_40e0!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.WEST;
_40de.x+=_40e0;
}
}
if((_40dc&SnapToHelper.SOUTH)!=0){
var _40e1=this.getCorrectionFor(this.rows,_40dd.getY()-1,1);
if(_40e1!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.SOUTH;
_40de.y+=_40e1;
}
}
if((_40dc&SnapToHelper.NORTH)!=0){
var _40e2=this.getCorrectionFor(this.rows,_40dd.getY(),-1);
if(_40e2!=SnapToGeometry.THRESHOLD){
_40dc&=~SnapToHelper.NORTH;
_40de.y+=_40e2;
}
}
return _40dc;
};
SnapToGeometry.prototype.snapRectangle=function(_40e3,_40e4){
var _40e5=_40e3.getTopLeft();
var _40e6=_40e3.getBottomRight();
var _40e7=this.snapPoint(SnapToHelper.NORTH_WEST,_40e3.getTopLeft(),_40e5);
_40e4.x=_40e5.x;
_40e4.y=_40e5.y;
var _40e8=this.snapPoint(SnapToHelper.SOUTH_EAST,_40e3.getBottomRight(),_40e6);
if(_40e7&SnapToHelper.WEST){
_40e4.x=_40e6.x-_40e3.getWidth();
}
if(_40e7&SnapToHelper.NORTH){
_40e4.y=_40e6.y-_40e3.getHeight();
}
return _40e7|_40e8;
};
SnapToGeometry.prototype.populateRowsAndCols=function(){
this.rows=new Array();
this.cols=new Array();
var _40e9=this.workflow.getDocument().getFigures();
var index=0;
for(var i=0;i<_40e9.getSize();i++){
var _40ec=_40e9.get(i);
if(_40ec!=this.workflow.getCurrentSelection()){
var _40ed=_40ec.getBounds();
this.cols[index*3]=new SnapToGeometryEntry(-1,_40ed.getX());
this.rows[index*3]=new SnapToGeometryEntry(-1,_40ed.getY());
this.cols[index*3+1]=new SnapToGeometryEntry(0,_40ed.x+(_40ed.getWidth()-1)/2);
this.rows[index*3+1]=new SnapToGeometryEntry(0,_40ed.y+(_40ed.getHeight()-1)/2);
this.cols[index*3+2]=new SnapToGeometryEntry(1,_40ed.getRight()-1);
this.rows[index*3+2]=new SnapToGeometryEntry(1,_40ed.getBottom()-1);
index++;
}
}
};
SnapToGeometry.prototype.getCorrectionFor=function(_40ee,value,side){
var _40f1=SnapToGeometry.THRESHOLD;
var _40f2=SnapToGeometry.THRESHOLD;
for(var i=0;i<_40ee.length;i++){
var entry=_40ee[i];
var _40f5;
if(entry.type==-1&&side!=0){
_40f5=Math.abs(value-entry.location);
if(_40f5<_40f1){
_40f1=_40f5;
_40f2=entry.location-value;
}
}else{
if(entry.type==0&&side==0){
_40f5=Math.abs(value-entry.location);
if(_40f5<_40f1){
_40f1=_40f5;
_40f2=entry.location-value;
}
}else{
if(entry.type==1&&side!=0){
_40f5=Math.abs(value-entry.location);
if(_40f5<_40f1){
_40f1=_40f5;
_40f2=entry.location-value;
}
}
}
}
}
return _40f2;
};
SnapToGeometry.prototype.onSetDocumentDirty=function(){
this.rows=null;
this.cols=null;
};
Border=function(){
this.color=null;
};
Border.prototype.type="Border";
Border.prototype.dispose=function(){
this.color=null;
};
Border.prototype.getHTMLStyle=function(){
return "";
};
Border.prototype.setColor=function(c){
this.color=c;
};
Border.prototype.getColor=function(){
return this.color;
};
Border.prototype.refresh=function(){
};
LineBorder=function(width){
Border.call(this);
this.width=1;
if(width){
this.width=width;
}
this.figure=null;
};
LineBorder.prototype=new Border;
LineBorder.prototype.type="LineBorder";
LineBorder.prototype.dispose=function(){
Border.prototype.dispose.call(this);
this.figure=null;
};
LineBorder.prototype.setLineWidth=function(w){
this.width=w;
if(this.figure!=null){
this.figure.html.style.border=this.getHTMLStyle();
}
};
LineBorder.prototype.getHTMLStyle=function(){
if(this.getColor()!=null){
return this.width+"px solid "+this.getColor().getHTMLStyle();
}
return this.width+"px solid black";
};
LineBorder.prototype.refresh=function(){
this.setLineWidth(this.width);
};
Figure=function(){
this.construct();
};
Figure.prototype.type="Figure";
Figure.ZOrderBaseIndex=100;
Figure.setZOrderBaseIndex=function(index){
Figure.ZOrderBaseIndex=index;
};
Figure.prototype.construct=function(){
this.lastDragStartTime=0;
this.x=0;
this.y=0;
this.border=null;
this.setDimension(10,10);
this.id=this.generateUId();
this.html=this.createHTMLElement();
this.canvas=null;
this.workflow=null;
this.draggable=null;
this.parent=null;
this.isMoving=false;
this.canSnapToHelper=true;
this.snapToGridAnchor=new Point(0,0);
this.timer=-1;
this.setDeleteable(true);
this.setCanDrag(true);
this.setResizeable(true);
this.setSelectable(true);
this.properties=new Object();
this.moveListener=new ArrayList();
};
Figure.prototype.dispose=function(){
this.canvas=null;
this.workflow=null;
this.moveListener=null;
if(this.draggable!=null){
this.draggable.removeEventListener("mouseenter",this.tmpMouseEnter);
this.draggable.removeEventListener("mouseleave",this.tmpMouseLeave);
this.draggable.removeEventListener("dragend",this.tmpDragend);
this.draggable.removeEventListener("dragstart",this.tmpDragstart);
this.draggable.removeEventListener("drag",this.tmpDrag);
this.draggable.removeEventListener("dblclick",this.tmpDoubleClick);
this.draggable.node=null;
}
this.draggable=null;
if(this.border!=null){
this.border.dispose();
}
this.border=null;
if(this.parent!=null){
this.parent.removeChild(this);
}
};
Figure.prototype.getProperties=function(){
return this.properties;
};
Figure.prototype.getProperty=function(key){
return this.properties[key];
};
Figure.prototype.setProperty=function(key,value){
this.properties[key]=value;
this.setDocumentDirty();
};
Figure.prototype.getId=function(){
return this.id;
};
Figure.prototype.setCanvas=function(_3deb){
this.canvas=_3deb;
};
Figure.prototype.getWorkflow=function(){
return this.workflow;
};
Figure.prototype.setWorkflow=function(_3dec){
if(this.draggable==null){
this.html.tabIndex="0";
var oThis=this;
this.keyDown=function(event){
event.cancelBubble=true;
event.returnValue=true;
oThis.onKeyDown(event.keyCode,event.ctrlKey);
};
if(this.html.addEventListener){
this.html.addEventListener("keydown",this.keyDown,false);
}else{
if(this.html.attachEvent){
this.html.attachEvent("onkeydown",this.keyDown);
}
}
this.draggable=new Draggable(this.html,Draggable.DRAG_X|Draggable.DRAG_Y);
this.draggable.node=this;
this.tmpContextMenu=function(_3def){
oThis.onContextMenu(oThis.x+_3def.x,_3def.y+oThis.y);
};
this.tmpMouseEnter=function(_3df0){
oThis.onMouseEnter();
};
this.tmpMouseLeave=function(_3df1){
oThis.onMouseLeave();
};
this.tmpDragend=function(_3df2){
oThis.onDragend();
};
this.tmpDragstart=function(_3df3){
var w=oThis.workflow;
w.showMenu(null);
if(oThis.workflow.toolPalette&&oThis.workflow.toolPalette.activeTool){
_3df3.returnValue=false;
oThis.workflow.onMouseDown(oThis.x+_3df3.x,_3df3.y+oThis.y);
oThis.workflow.onMouseUp(oThis.x+_3df3.x,_3df3.y+oThis.y);
return;
}
_3df3.returnValue=oThis.onDragstart(_3df3.x,_3df3.y);
};
this.tmpDrag=function(_3df5){
oThis.onDrag();
};
this.tmpDoubleClick=function(_3df6){
oThis.onDoubleClick();
};
this.draggable.addEventListener("contextmenu",this.tmpContextMenu);
this.draggable.addEventListener("mouseenter",this.tmpMouseEnter);
this.draggable.addEventListener("mouseleave",this.tmpMouseLeave);
this.draggable.addEventListener("dragend",this.tmpDragend);
this.draggable.addEventListener("dragstart",this.tmpDragstart);
this.draggable.addEventListener("drag",this.tmpDrag);
this.draggable.addEventListener("dblclick",this.tmpDoubleClick);
}
this.workflow=_3dec;
};
Figure.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height=this.width+"px";
item.style.width=this.height+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.outline="none";
item.style.zIndex=""+Figure.ZOrderBaseIndex;
return item;
};
Figure.prototype.setParent=function(_3df8){
this.parent=_3df8;
};
Figure.prototype.getParent=function(){
return this.parent;
};
Figure.prototype.getZOrder=function(){
return this.html.style.zIndex;
};
Figure.prototype.setZOrder=function(index){
this.html.style.zIndex=index;
};
Figure.prototype.hasFixedPosition=function(){
return false;
};
Figure.prototype.getMinWidth=function(){
return 5;
};
Figure.prototype.getMinHeight=function(){
return 5;
};
Figure.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
Figure.prototype.paint=function(){
};
Figure.prototype.setBorder=function(_3dfa){
if(this.border!=null){
this.border.figure=null;
}
this.border=_3dfa;
this.border.figure=this;
this.border.refresh();
this.setDocumentDirty();
};
Figure.prototype.onContextMenu=function(x,y){
var menu=this.getContextMenu();
if(menu!=null){
this.workflow.showMenu(menu,x,y);
}
};
Figure.prototype.getContextMenu=function(){
return null;
};
Figure.prototype.onDoubleClick=function(){
};
Figure.prototype.onMouseEnter=function(){
};
Figure.prototype.onMouseLeave=function(){
};
Figure.prototype.onDrag=function(){
this.x=this.draggable.getLeft();
this.y=this.draggable.getTop();
if(this.isMoving==false){
this.isMoving=true;
this.setAlpha(0.5);
}
this.fireMoveEvent();
};
Figure.prototype.onDragend=function(){
if(this.getWorkflow().getEnableSmoothFigureHandling()==true){
var _3dfe=this;
var _3dff=function(){
if(_3dfe.alpha<1){
_3dfe.setAlpha(Math.min(1,_3dfe.alpha+0.05));
}else{
window.clearInterval(_3dfe.timer);
_3dfe.timer=-1;
}
};
if(_3dfe.timer>0){
window.clearInterval(_3dfe.timer);
}
_3dfe.timer=window.setInterval(_3dff,20);
}else{
this.setAlpha(1);
}
this.command.setPosition(this.x,this.y);
this.workflow.commandStack.execute(this.command);
this.command=null;
this.isMoving=false;
this.workflow.hideSnapToHelperLines();
this.fireMoveEvent();
};
Figure.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
this.command=new CommandMove(this,this.x,this.y);
return true;
};
Figure.prototype.setCanDrag=function(flag){
this.canDrag=flag;
if(flag){
this.html.style.cursor="move";
}else{
this.html.style.cursor=null;
}
};
Figure.prototype.setAlpha=function(_3e03){
if(this.alpha==_3e03){
return;
}
try{
this.html.style.MozOpacity=_3e03;
}
catch(exc){
}
try{
this.html.style.opacity=_3e03;
}
catch(exc){
}
try{
var _3e04=Math.round(_3e03*100);
if(_3e04>=99){
this.html.style.filter="";
}else{
this.html.style.filter="alpha(opacity="+_3e04+")";
}
}
catch(exc){
}
this.alpha=_3e03;
};
Figure.prototype.setDimension=function(w,h){
this.width=Math.max(this.getMinWidth(),w);
this.height=Math.max(this.getMinHeight(),h);
if(this.html==null){
return;
}
this.html.style.width=this.width+"px";
this.html.style.height=this.height+"px";
this.fireMoveEvent();
if(this.workflow!=null&&this.workflow.getCurrentSelection()==this){
this.workflow.showResizeHandles(this);
}
};
Figure.prototype.setPosition=function(xPos,yPos){
this.x=xPos;
this.y=yPos;
if(this.html==null){
return;
}
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
this.fireMoveEvent();
if(this.workflow!=null&&this.workflow.getCurrentSelection()==this){
this.workflow.showResizeHandles(this);
}
};
Figure.prototype.isResizeable=function(){
return this.resizeable;
};
Figure.prototype.setResizeable=function(flag){
this.resizeable=flag;
};
Figure.prototype.isSelectable=function(){
return this.selectable;
};
Figure.prototype.setSelectable=function(flag){
this.selectable=flag;
};
Figure.prototype.isStrechable=function(){
return true;
};
Figure.prototype.isDeleteable=function(){
return this.deleteable;
};
Figure.prototype.setDeleteable=function(flag){
this.deleteable=flag;
};
Figure.prototype.setCanSnapToHelper=function(flag){
this.canSnapToHelper=flag;
};
Figure.prototype.getCanSnapToHelper=function(){
return this.canSnapToHelper;
};
Figure.prototype.getSnapToGridAnchor=function(){
return this.snapToGridAnchor;
};
Figure.prototype.setSnapToGridAnchor=function(point){
this.snapToGridAnchor=point;
};
Figure.prototype.getBounds=function(){
return new Dimension(this.getX(),this.getY(),this.getWidth(),this.getHeight());
};
Figure.prototype.getWidth=function(){
return this.width;
};
Figure.prototype.getHeight=function(){
return this.height;
};
Figure.prototype.getY=function(){
return this.y;
};
Figure.prototype.getX=function(){
return this.x;
};
Figure.prototype.getAbsoluteY=function(){
return this.y;
};
Figure.prototype.getAbsoluteX=function(){
return this.x;
};
Figure.prototype.onKeyDown=function(_3e0e,ctrl){
if(_3e0e==46&&this.isDeleteable()==true){
this.workflow.commandStack.execute(new CommandDelete(this));
}
if(ctrl){
this.workflow.onKeyDown(_3e0e,ctrl);
}
};
Figure.prototype.getPosition=function(){
return new Point(this.x,this.y);
};
Figure.prototype.isOver=function(iX,iY){
var x=this.getAbsoluteX();
var y=this.getAbsoluteY();
var iX2=x+this.width;
var iY2=y+this.height;
return (iX>=x&&iX<=iX2&&iY>=y&&iY<=iY2);
};
Figure.prototype.attachMoveListener=function(_3e16){
if(_3e16==null||this.moveListener==null){
return;
}
this.moveListener.add(_3e16);
};
Figure.prototype.detachMoveListener=function(_3e17){
if(_3e17==null||this.moveListener==null){
return;
}
this.moveListener.remove(_3e17);
};
Figure.prototype.fireMoveEvent=function(){
this.setDocumentDirty();
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
this.moveListener.get(i).onOtherFigureMoved(this);
}
};
Figure.prototype.onOtherFigureMoved=function(_3e1a){
};
Figure.prototype.setDocumentDirty=function(){
if(this.workflow!=null){
this.workflow.setDocumentDirty();
}
};
Figure.prototype.generateUId=function(){
var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var _3e1c=10;
var _3e1d=10;
nbTry=0;
while(nbTry<1000){
var id="";
for(var i=0;i<_3e1c;i++){
var rnum=Math.floor(Math.random()*chars.length);
id+=chars.substring(rnum,rnum+1);
}
elem=document.getElementById(id);
if(!elem){
return id;
}
nbTry+=1;
}
return null;
};
Figure.prototype.disableTextSelection=function(e){
if(typeof e.onselectstart!="undefined"){
e.onselectstart=function(){
return false;
};
}else{
if(typeof e.style.MozUserSelect!="undefined"){
e.style.MozUserSelect="none";
}
}
};
Node=function(){
this.bgColor=null;
this.lineColor=new Color(128,128,255);
this.lineStroke=1;
this.ports=new ArrayList();
Figure.call(this);
};
Node.prototype=new Figure;
Node.prototype.type="Node";
Node.prototype.dispose=function(){
for(var i=0;i<this.ports.getSize();i++){
this.ports.get(i).dispose();
}
this.ports=null;
Figure.prototype.dispose.call(this);
};
Node.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.width="auto";
item.style.height="auto";
item.style.margin="0px";
item.style.padding="0px";
if(this.lineColor!=null){
item.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}
item.style.fontSize="1px";
if(this.bgColor!=null){
item.style.backgroundColor=this.bgColor.getHTMLStyle();
}
return item;
};
Node.prototype.paint=function(){
Figure.prototype.paint.call(this);
for(var i=0;i<this.ports.getSize();i++){
this.ports.get(i).paint();
}
};
Node.prototype.getPorts=function(){
return this.ports;
};
Node.prototype.getPort=function(_32a7){
if(this.ports==null){
return null;
}
for(var i=0;i<this.ports.getSize();i++){
var port=this.ports.get(i);
if(port.getName()==_32a7){
return port;
}
}
};
Node.prototype.addPort=function(port,x,y){
this.ports.add(port);
port.setOrigin(x,y);
port.setPosition(x,y);
port.setParent(this);
port.setDeleteable(false);
this.html.appendChild(port.getHTMLElement());
if(this.workflow!=null){
this.workflow.registerPort(port);
}
};
Node.prototype.removePort=function(port){
if(this.ports!=null){
this.ports.removeElementAt(this.ports.indexOf(port));
}
try{
this.html.removeChild(port.getHTMLElement());
}
catch(exc){
}
if(this.workflow!=null){
this.workflow.unregisterPort(port);
}
};
Node.prototype.setWorkflow=function(_32ae){
var _32af=this.workflow;
Figure.prototype.setWorkflow.call(this,_32ae);
if(_32af!=null){
for(var i=0;i<this.ports.getSize();i++){
_32af.unregisterPort(this.ports.get(i));
}
}
if(this.workflow!=null){
for(var i=0;i<this.ports.getSize();i++){
this.workflow.registerPort(this.ports.get(i));
}
}
};
Node.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Node.prototype.getBackgroundColor=function(){
return this.bgColor;
};
Node.prototype.setColor=function(color){
this.lineColor=color;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border="0px";
}
};
Node.prototype.setLineWidth=function(w){
this.lineStroke=w;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border="0px";
}
};
VectorFigure=function(){
this.bgColor=null;
this.lineColor=new Color(0,0,0);
this.stroke=1;
this.graphics=null;
Node.call(this);
};
VectorFigure.prototype=new Node;
VectorFigure.prototype.type="VectorFigure";
VectorFigure.prototype.dispose=function(){
Node.prototype.dispose.call(this);
this.bgColor=null;
this.lineColor=null;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
VectorFigure.prototype.createHTMLElement=function(){
var item=Node.prototype.createHTMLElement.call(this);
item.style.border="0px";
item.style.backgroundColor="transparent";
return item;
};
VectorFigure.prototype.setWorkflow=function(_3e71){
Node.prototype.setWorkflow.call(this,_3e71);
if(this.workflow==null){
this.graphics.clear();
this.graphics=null;
}
};
VectorFigure.prototype.paint=function(){
if(this.graphics==null){
this.graphics=new jsGraphics(this.id);
}else{
this.graphics.clear();
}
Node.prototype.paint.call(this);
for(var i=0;i<this.ports.getSize();i++){
this.getHTMLElement().appendChild(this.ports.get(i).getHTMLElement());
}
};
VectorFigure.prototype.setDimension=function(w,h){
Node.prototype.setDimension.call(this,w,h);
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.setTaskCount=function(_40c0){
}
VectorFigure.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.getBackgroundColor=function(){
return this.bgColor;
};
VectorFigure.prototype.setLineWidth=function(w){
this.stroke=w;
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.setColor=function(color){
this.lineColor=color;
if(this.graphics!=null){
this.paint();
}
};
VectorFigure.prototype.getColor=function(){
return this.lineColor;
};
SVGFigure=function(width,_30b2){
this.bgColor=null;
this.lineColor=new Color(0,0,0);
this.stroke=1;
this.context=null;
Node.call(this);
if(width&&_30b2){
this.setDimension(width,_30b2);
}
};
SVGFigure.prototype=new Node;
SVGFigure.prototype.type="SVGFigure";
SVGFigure.prototype.createHTMLElement=function(){
var item=new MooCanvas(this.id,{width:this.getWidth(),height:this.getHeight()});
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.zIndex=""+Figure.ZOrderBaseIndex;
this.context=item.getContext("2d");
return item;
};
SVGFigure.prototype.paint=function(){
this.context.clearRect(0,0,this.getWidth(),this.getHeight());
this.context.fillStyle="rgba(200,0,0,0.3)";
this.context.fillRect(0,0,this.getWidth(),this.getHeight());
};
SVGFigure.prototype.setDimension=function(w,h){
Node.prototype.setDimension.call(this,w,h);
this.html.width=w;
this.html.height=h;
if(this.context!=null){
this.paint();
}
};
SVGFigure.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.graphics!=null){
this.paint();
}
};
SVGFigure.prototype.getBackgroundColor=function(){
return this.bgColor;
};
SVGFigure.prototype.setLineWidth=function(w){
this.stroke=w;
if(this.context!=null){
this.paint();
}
};
SVGFigure.prototype.setColor=function(color){
this.lineColor=color;
if(this.context!=null){
this.paint();
}
};
SVGFigure.prototype.getColor=function(){
return this.lineColor;
};
Label=function(msg){
this.msg=msg;
this.bgColor=null;
this.color=new Color(0,0,0);
this.fontSize=10;
this.textNode=null;
this.align="center";
Figure.call(this);
};
Label.prototype=new Figure;
Label.prototype.type="Label";
Label.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
this.textNode=document.createTextNode(this.msg);
item.appendChild(this.textNode);
item.style.color=this.color.getHTMLStyle();
item.style.fontSize=this.fontSize+"pt";
item.style.width="auto";
item.style.height="auto";
item.style.paddingLeft="3px";
item.style.paddingRight="3px";
item.style.textAlign=this.align;
if(this.bgColor!=null){
item.style.backgroundColor=this.bgColor.getHTMLStyle();
}
return item;
};
Label.prototype.isResizeable=function(){
return false;
};
Label.prototype.setWordwrap=function(flag){
this.html.style.whiteSpace=flag?"wrap":"nowrap";
};
Label.prototype.setAlign=function(align){
this.align=align;
this.html.style.textAlign=align;
};
Label.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Label.prototype.setColor=function(color){
this.color=color;
this.html.style.color=this.color.getHTMLStyle();
};
Label.prototype.setFontSize=function(size){
this.fontSize=size;
this.html.style.fontSize=this.fontSize+"pt";
};
Label.prototype.getWidth=function(){
if(window.getComputedStyle){
return parseInt(getComputedStyle(this.html,"").getPropertyValue("width"));
}
return parseInt(this.html.clientWidth);
};
Label.prototype.getHeight=function(){
if(window.getComputedStyle){
return parseInt(getComputedStyle(this.html,"").getPropertyValue("height"));
}
return parseInt(this.html.clientHeight);
};
Label.prototype.getText=function(){
this.msg=text;
};
Label.prototype.setText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createTextNode(this.msg);
this.html.appendChild(this.textNode);
};
Label.prototype.setStyledText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createElement("div");
this.textNode.style.whiteSpace="nowrap";
this.textNode.innerHTML=text;
this.html.appendChild(this.textNode);
};
Oval=function(){
VectorFigure.call(this);
};
Oval.prototype=new VectorFigure;
Oval.prototype.type="Oval";
Oval.prototype.paint=function(){
VectorFigure.prototype.paint.call(this);
this.graphics.setStroke(this.stroke);
if(this.bgColor!=null){
this.graphics.setColor(this.bgColor.getHTMLStyle());
this.graphics.fillOval(0,0,this.getWidth()-1,this.getHeight()-1);
}
if(this.lineColor!=null){
this.graphics.setColor(this.lineColor.getHTMLStyle());
this.graphics.drawOval(0,0,this.getWidth()-1,this.getHeight()-1);
}
this.graphics.paint();
};
Circle=function(_3f5f){
Oval.call(this);
if(_3f5f){
this.setDimension(_3f5f,_3f5f);
}
};
Circle.prototype=new Oval;
Circle.prototype.type="Circle";
Circle.prototype.setDimension=function(w,h){
if(w>h){
Oval.prototype.setDimension.call(this,w,w);
}else{
Oval.prototype.setDimension.call(this,h,h);
}
};
Circle.prototype.isStrechable=function(){
return false;
};
Rectangle=function(width,_3e35){
this.bgColor=null;
this.lineColor=new Color(0,0,0);
this.lineStroke=1;
Figure.call(this);
if(width&&_3e35){
this.setDimension(width,_3e35);
}
};
Rectangle.prototype=new Figure;
Rectangle.prototype.type="Rectangle";
Rectangle.prototype.dispose=function(){
Figure.prototype.dispose.call(this);
this.bgColor=null;
this.lineColor=null;
};
Rectangle.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.width="auto";
item.style.height="auto";
item.style.margin="0px";
item.style.padding="0px";
item.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
item.style.fontSize="1px";
item.style.lineHeight="1px";
item.innerHTML=" ";
if(this.bgColor!=null){
item.style.backgroundColor=this.bgColor.getHTMLStyle();
}
return item;
};
Rectangle.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Rectangle.prototype.getBackgroundColor=function(){
return this.bgColor;
};
Rectangle.prototype.setColor=function(color){
this.lineColor=color;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border=this.lineStroke+"0px";
}
};
Rectangle.prototype.getColor=function(){
return this.lineColor;
};
Rectangle.prototype.getWidth=function(){
return Figure.prototype.getWidth.call(this)+2*this.lineStroke;
};
Rectangle.prototype.getHeight=function(){
return Figure.prototype.getHeight.call(this)+2*this.lineStroke;
};
Rectangle.prototype.setDimension=function(w,h){
return Figure.prototype.setDimension.call(this,w-2*this.lineStroke,h-2*this.lineStroke);
};
Rectangle.prototype.setLineWidth=function(w){
var diff=w-this.lineStroke;
this.setDimension(this.getWidth()-2*diff,this.getHeight()-2*diff);
this.lineStroke=w;
var c="transparent";
if(this.lineColor!=null){
c=this.lineColor.getHTMLStyle();
}
this.html.style.border=this.lineStroke+"px solid "+c;
};
Rectangle.prototype.getLineWidth=function(){
return this.lineStroke;
};
ImageFigure=function(url){
this.url=url;
Node.call(this);
this.setDimension(40,40);
};
ImageFigure.prototype=new Node;
ImageFigure.prototype.type="Image";
ImageFigure.prototype.createHTMLElement=function(){
var item=Node.prototype.createHTMLElement.call(this);
item.style.width=this.width+"px";
item.style.height=this.height+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.border="0px";
if(this.url!=null){
item.style.backgroundImage="url("+this.url+")";
}else{
item.style.backgroundImage="";
}
return item;
};
ImageFigure.prototype.setColor=function(color){
};
ImageFigure.prototype.isResizeable=function(){
return false;
};
ImageFigure.prototype.setImage=function(url){
this.url=url;
if(this.url!=null){
this.html.style.backgroundImage="url("+this.url+")";
}else{
this.html.style.backgroundImage="";
}
};
Port=function(_41c2,_41c3){
Corona=function(){
};
Corona.prototype=new Circle;
Corona.prototype.setAlpha=function(_41c4){
Circle.prototype.setAlpha.call(this,Math.min(0.3,_41c4));
};
if(_41c2==null){
this.currentUIRepresentation=new Circle();
}else{
this.currentUIRepresentation=_41c2;
}
if(_41c3==null){
this.connectedUIRepresentation=new Circle();
this.connectedUIRepresentation.setColor(null);
}else{
this.connectedUIRepresentation=_41c3;
}
this.disconnectedUIRepresentation=this.currentUIRepresentation;
this.hideIfConnected=false;
this.uiRepresentationAdded=true;
this.parentNode=null;
this.originX=0;
this.originY=0;
this.coronaWidth=10;
this.corona=null;
Rectangle.call(this);
this.setDimension(8,8);
this.setBackgroundColor(new Color(100,180,100));
this.setColor(new Color(90,150,90));
Rectangle.prototype.setColor.call(this,null);
this.dropable=new DropTarget(this.html);
this.dropable.node=this;
this.dropable.addEventListener("dragenter",function(_41c5){
_41c5.target.node.onDragEnter(_41c5.relatedTarget.node);
});
this.dropable.addEventListener("dragleave",function(_41c6){
_41c6.target.node.onDragLeave(_41c6.relatedTarget.node);
});
this.dropable.addEventListener("drop",function(_41c7){
_41c7.relatedTarget.node.onDrop(_41c7.target.node);
});
};
Port.prototype=new Rectangle;
Port.prototype.type="Port";
Port.ZOrderBaseIndex=5000;
Port.setZOrderBaseIndex=function(index){
Port.ZOrderBaseIndex=index;
};
Port.prototype.setHideIfConnected=function(flag){
this.hideIfConnected=flag;
};
Port.prototype.dispose=function(){
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
var _41cc=this.moveListener.get(i);
this.parentNode.workflow.removeFigure(_41cc);
_41cc.dispose();
}
Rectangle.prototype.dispose.call(this);
this.parentNode=null;
this.dropable.node=null;
this.dropable=null;
this.disconnectedUIRepresentation.dispose();
this.connectedUIRepresentation.dispose();
};
Port.prototype.createHTMLElement=function(){
var item=Rectangle.prototype.createHTMLElement.call(this);
item.style.zIndex=Port.ZOrderBaseIndex;
this.currentUIRepresentation.html.zIndex=Port.ZOrderBaseIndex;
item.appendChild(this.currentUIRepresentation.html);
this.uiRepresentationAdded=true;
return item;
};
Port.prototype.setUiRepresentation=function(_41ce){
if(_41ce==null){
_41ce=new Figure();
}
if(this.uiRepresentationAdded){
//Commented for IE* errors while changing the shape from context menu
//this.html.removeChild(this.currentUIRepresentation.getHTMLElement());
}
this.html.appendChild(_41ce.getHTMLElement());
_41ce.paint();
this.currentUIRepresentation=_41ce;
};
Port.prototype.onMouseEnter=function(){
this.setLineWidth(2);
};
Port.prototype.onMouseLeave=function(){
this.setLineWidth(0);
};
Port.prototype.setDimension=function(width,_41d0){
Rectangle.prototype.setDimension.call(this,width,_41d0);
this.connectedUIRepresentation.setDimension(width,_41d0);
this.disconnectedUIRepresentation.setDimension(width,_41d0);
this.setPosition(this.x,this.y);
};
Port.prototype.setBackgroundColor=function(color){
this.currentUIRepresentation.setBackgroundColor(color);
};
Port.prototype.getBackgroundColor=function(){
return this.currentUIRepresentation.getBackgroundColor();
};
Port.prototype.getConnections=function(){
var _41d2=new ArrayList();
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
var _41d5=this.moveListener.get(i);
if(_41d5 instanceof Connection){
_41d2.add(_41d5);
}
}
return _41d2;
};
Port.prototype.setColor=function(color){
this.currentUIRepresentation.setColor(color);
};
Port.prototype.getColor=function(){
return this.currentUIRepresentation.getColor();
};
Port.prototype.setLineWidth=function(width){
this.currentUIRepresentation.setLineWidth(width);
};
Port.prototype.getLineWidth=function(){
return this.currentUIRepresentation.getLineWidth();
};
Port.prototype.paint=function(){
this.currentUIRepresentation.paint();
};
Port.prototype.setPosition=function(xPos,yPos){
this.originX=xPos;
this.originY=yPos;
Rectangle.prototype.setPosition.call(this,xPos,yPos);
if(this.html==null){
return;
}
this.html.style.left=(this.x-this.getWidth()/2)+"px";
this.html.style.top=(this.y-this.getHeight()/2)+"px";
};
Port.prototype.setParent=function(_41da){
if(this.parentNode!=null){
this.parentNode.detachMoveListener(this);
}
this.parentNode=_41da;
if(this.parentNode!=null){
this.parentNode.attachMoveListener(this);
}
};
Port.prototype.attachMoveListener=function(_41db){
Rectangle.prototype.attachMoveListener.call(this,_41db);
if(this.hideIfConnected==true){
this.setUiRepresentation(this.connectedUIRepresentation);
}
};
Port.prototype.detachMoveListener=function(_41dc){
Rectangle.prototype.detachMoveListener.call(this,_41dc);
if(this.getConnections().getSize()==0){
this.setUiRepresentation(this.disconnectedUIRepresentation);
}
};
Port.prototype.getParent=function(){
return this.parentNode;
};
Port.prototype.onDrag=function(){
Rectangle.prototype.onDrag.call(this);
this.parentNode.workflow.showConnectionLine(this.parentNode.x+this.x,this.parentNode.y+this.y,this.parentNode.x+this.originX,this.parentNode.y+this.originY);
};
Port.prototype.getCoronaWidth=function(){
return this.coronaWidth;
};
Port.prototype.setCoronaWidth=function(width){
this.coronaWidth=width;
};
Port.prototype.onDragend=function(){
this.setAlpha(1);
this.setPosition(this.originX,this.originY);
this.parentNode.workflow.hideConnectionLine();
};
Port.prototype.setOrigin=function(x,y){
this.originX=x;
this.originY=y;
};
Port.prototype.onDragEnter=function(port){
this.parentNode.workflow.connectionLine.setColor(new Color(0,150,0));
this.parentNode.workflow.connectionLine.setLineWidth(3);
this.showCorona(true);
};
Port.prototype.onDragLeave=function(port){
this.parentNode.workflow.connectionLine.setColor(new Color(0,0,0));
this.parentNode.workflow.connectionLine.setLineWidth(1);
this.showCorona(false);
};
Port.prototype.onDrop=function(port){
if(this.parentNode.id==port.parentNode.id){
}else{
var _41e3=new CommandConnect(this.parentNode.workflow,port,this);
this.parentNode.workflow.getCommandStack().execute(_41e3);
}
};
Port.prototype.getAbsolutePosition=function(){
return new Point(this.getAbsoluteX(),this.getAbsoluteY());
};
Port.prototype.getAbsoluteBounds=function(){
return new Dimension(this.getAbsoluteX(),this.getAbsoluteY(),this.getWidth(),this.getHeight());
};
Port.prototype.getAbsoluteY=function(){
return this.originY+this.parentNode.getY();
};
Port.prototype.getAbsoluteX=function(){
return this.originX+this.parentNode.getX();
};
Port.prototype.onOtherFigureMoved=function(_41e4){
this.fireMoveEvent();
};
Port.prototype.getName=function(){
return this.getProperty("name");
};
Port.prototype.setName=function(name){
this.setProperty("name",name);
};
Port.prototype.isOver=function(iX,iY){
var x=this.getAbsoluteX()-this.coronaWidth-this.getWidth()/2;
var y=this.getAbsoluteY()-this.coronaWidth-this.getHeight()/2;
var iX2=x+this.width+(this.coronaWidth*2)+this.getWidth()/2;
var iY2=y+this.height+(this.coronaWidth*2)+this.getHeight()/2;
return (iX>=x&&iX<=iX2&&iY>=y&&iY<=iY2);
};
Port.prototype.showCorona=function(flag,_41ed){
if(flag==true){
this.corona=new Corona();
this.corona.setAlpha(0.3);
this.corona.setBackgroundColor(new Color(0,125,125));
this.corona.setColor(null);
this.corona.setDimension(this.getWidth()+(this.getCoronaWidth()*2),this.getWidth()+(this.getCoronaWidth()*2));
this.parentNode.getWorkflow().addFigure(this.corona,this.getAbsoluteX()-this.getCoronaWidth()-this.getWidth()/2,this.getAbsoluteY()-this.getCoronaWidth()-this.getHeight()/2);
}else{
if(flag==false&&this.corona!=null){
this.parentNode.getWorkflow().removeFigure(this.corona);
this.corona=null;
}
}
};
InputPort=function(_4067){
Port.call(this,_4067);
};
InputPort.prototype=new Port;
InputPort.prototype.type="InputPort";
InputPort.prototype.onDrop=function(port){
if(port.getMaxFanOut&&port.getMaxFanOut()<=port.getFanOut()){
return;
}
if(this.parentNode.id==port.parentNode.id){
}else{
if(port instanceof OutputPort){
var _4069=new CommandConnect(this.parentNode.workflow,port,this);
this.parentNode.workflow.getCommandStack().execute(_4069);
}
}
};
InputPort.prototype.onDragEnter=function(port){
if(port instanceof OutputPort){
Port.prototype.onDragEnter.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof InputPort){
Port.prototype.onDragEnter.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof InputPort){
Port.prototype.onDragEnter.call(this,line.getTarget());
}
}
}
}
};
InputPort.prototype.onDragLeave=function(port){
if(port instanceof OutputPort){
Port.prototype.onDragLeave.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof InputPort){
Port.prototype.onDragLeave.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof InputPort){
Port.prototype.onDragLeave.call(this,line.getTarget());
}
}
}
}
};
OutputPort=function(_357f){
Port.call(this,_357f);
this.maxFanOut=100;
};
OutputPort.prototype=new Port;
OutputPort.prototype.type="OutputPort";
OutputPort.prototype.onDrop=function(port){
if(this.getMaxFanOut()<=this.getFanOut()){
return;
}
if(this.parentNode.id==port.parentNode.id){
}else{
if(port instanceof InputPort){
var _3581=new CommandConnect(this.parentNode.workflow,this,port);
this.parentNode.workflow.getCommandStack().execute(_3581);
}
}
};
OutputPort.prototype.onDragEnter=function(port){
if(this.getMaxFanOut()<=this.getFanOut()){
return;
}
if(port instanceof InputPort){
Port.prototype.onDragEnter.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof OutputPort){
Port.prototype.onDragEnter.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof OutputPort){
Port.prototype.onDragEnter.call(this,line.getTarget());
}
}
}
}
};
OutputPort.prototype.onDragLeave=function(port){
if(port instanceof InputPort){
Port.prototype.onDragLeave.call(this,port);
}else{
if(port instanceof LineStartResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getSource() instanceof OutputPort){
Port.prototype.onDragLeave.call(this,line.getSource());
}
}else{
if(port instanceof LineEndResizeHandle){
var line=this.workflow.currentSelection;
if(line instanceof Connection&&line.getTarget() instanceof OutputPort){
Port.prototype.onDragLeave.call(this,line.getTarget());
}
}
}
}
};
OutputPort.prototype.onDragstart=function(x,y){
if(this.maxFanOut==-1){
return true;
}
if(this.getMaxFanOut()<=this.getFanOut()){
return false;
}
return true;
};
OutputPort.prototype.setMaxFanOut=function(count){
this.maxFanOut=count;
};
OutputPort.prototype.getMaxFanOut=function(){
return this.maxFanOut;
};
OutputPort.prototype.getFanOut=function(){
if(this.getParent().workflow==null){
return 0;
}
var count=0;
var lines=this.getParent().workflow.getLines();
var size=lines.getSize();
for(var i=0;i<size;i++){
var line=lines.get(i);
if(line instanceof Connection){
if(line.getSource()==this){
count++;
}else{
if(line.getTarget()==this){
count++;
}
}
}
}
return count;
};
Line=function(){
this.lineColor=new Color(0,0,0);
this.stroke=1;
this.canvas=null;
this.workflow=null;
this.html=null;
this.graphics=null;
this.id=this.generateUId();
this.startX=30;
this.startY=30;
this.endX=100;
this.endY=100;
this.alpha=1;
this.isMoving=false;
this.zOrder=Line.ZOrderBaseIndex;
this.moveListener=new ArrayList();
this.setSelectable(true);
this.setDeleteable(true);
};
Line.ZOrderBaseIndex=200;
Line.setZOrderBaseIndex=function(index){
Line.ZOrderBaseIndex=index;
};
Line.prototype.dispose=function(){
this.canvas=null;
this.workflow=null;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
Line.prototype.getZOrder=function(){
return this.zOrder;
};
Line.prototype.setZOrder=function(index){
if(this.html!=null){
this.html.style.zIndex=index;
}
this.zOrder=index;
};
Line.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left="0px";
item.style.top="0px";
item.style.height="0px";
item.style.width="0px";
item.style.zIndex=this.zOrder;
return item;
};
Line.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
Line.prototype.getWorkflow=function(){
return this.workflow;
};
Line.prototype.isResizeable=function(){
return true;
};
Line.prototype.setCanvas=function(_3ecb){
this.canvas=_3ecb;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
Line.prototype.setWorkflow=function(_3ecc){
this.workflow=_3ecc;
if(this.graphics!=null){
this.graphics.clear();
}
this.graphics=null;
};
Line.prototype.paint=function(){
if(this.graphics==null){
this.graphics=new jsGraphics(this.id);
}else{
this.graphics.clear();
}
this.graphics.setStroke(this.stroke);
this.graphics.setColor(this.lineColor.getHTMLStyle());
this.graphics.drawLine(this.startX,this.startY,this.endX,this.endY);
this.graphics.paint();
};
Line.prototype.attachMoveListener=function(_3ecd){
this.moveListener.add(_3ecd);
};
Line.prototype.detachMoveListener=function(_3ece){
this.moveListener.remove(_3ece);
};
Line.prototype.fireMoveEvent=function(){
var size=this.moveListener.getSize();
for(var i=0;i<size;i++){
this.moveListener.get(i).onOtherFigureMoved(this);
}
};
Line.prototype.onOtherFigureMoved=function(_3ed1){
};
Line.prototype.setLineWidth=function(w){
this.stroke=w;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.setColor=function(color){
this.lineColor=color;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.getColor=function(){
return this.lineColor;
};
Line.prototype.setAlpha=function(_3ed4){
if(_3ed4==this.alpha){
return;
}
try{
this.html.style.MozOpacity=_3ed4;
}
catch(exc){
}
try{
this.html.style.opacity=_3ed4;
}
catch(exc){
}
try{
var _3ed5=Math.round(_3ed4*100);
if(_3ed5>=99){
this.html.style.filter="";
}else{
this.html.style.filter="alpha(opacity="+_3ed5+")";
}
}
catch(exc){
}
this.alpha=_3ed4;
};
Line.prototype.setStartPoint=function(x,y){
this.startX=x;
this.startY=y;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.setEndPoint=function(x,y){
this.endX=x;
this.endY=y;
if(this.graphics!=null){
this.paint();
}
this.setDocumentDirty();
};
Line.prototype.getStartX=function(){
return this.startX;
};
Line.prototype.getStartY=function(){
return this.startY;
};
Line.prototype.getStartPoint=function(){
return new Point(this.startX,this.startY);
};
Line.prototype.getEndX=function(){
return this.endX;
};
Line.prototype.getEndY=function(){
return this.endY;
};
Line.prototype.getEndPoint=function(){
return new Point(this.endX,this.endY);
};
Line.prototype.isSelectable=function(){
return this.selectable;
};
Line.prototype.setSelectable=function(flag){
this.selectable=flag;
};
Line.prototype.isDeleteable=function(){
return this.deleteable;
};
Line.prototype.setDeleteable=function(flag){
this.deleteable=flag;
};
Line.prototype.getLength=function(){
return Math.sqrt((this.startX-this.endX)*(this.startX-this.endX)+(this.startY-this.endY)*(this.startY-this.endY));
};
Line.prototype.getAngle=function(){
var _3edc=this.getLength();
var angle=-(180/Math.PI)*Math.asin((this.startY-this.endY)/_3edc);
if(angle<0){
if(this.endX<this.startX){
angle=Math.abs(angle)+180;
}else{
angle=360-Math.abs(angle);
}
}else{
if(this.endX<this.startX){
angle=180-angle;
}
}
return angle;
};
Line.prototype.onContextMenu=function(x,y){
var menu=this.getContextMenu();
if(menu!=null){
this.workflow.showMenu(menu,x,y);
}
};
Line.prototype.getContextMenu=function(){
return null;
};
Line.prototype.onDoubleClick=function(){
};
Line.prototype.setDocumentDirty=function(){
if(this.workflow!=null){
this.workflow.setDocumentDirty();
}
};
Line.prototype.generateUId=function(){
var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var _3ee2=10;
var _3ee3=10;
nbTry=0;
while(nbTry<1000){
var id="";
for(var i=0;i<_3ee2;i++){
var rnum=Math.floor(Math.random()*chars.length);
id+=chars.substring(rnum,rnum+1);
}
elem=document.getElementById(id);
if(!elem){
return id;
}
nbTry+=1;
}
return null;
};
Line.prototype.containsPoint=function(px,py){
return Line.hit(this.startX,this.startY,this.endX,this.endY,px,py);
};
Line.hit=function(X1,Y1,X2,Y2,px,py){
var _3eef=5;
X2-=X1;
Y2-=Y1;
px-=X1;
py-=Y1;
var _3ef0=px*X2+py*Y2;
var _3ef1;
if(_3ef0<=0){
_3ef1=0;
}else{
px=X2-px;
py=Y2-py;
_3ef0=px*X2+py*Y2;
if(_3ef0<=0){
_3ef1=0;
}else{
_3ef1=_3ef0*_3ef0/(X2*X2+Y2*Y2);
}
}
var lenSq=px*px+py*py-_3ef1;
if(lenSq<0){
lenSq=0;
}
return Math.sqrt(lenSq)<_3eef;
};
ConnectionRouter=function(){
};
ConnectionRouter.prototype.type="ConnectionRouter";
ConnectionRouter.prototype.getDirection=function(r,p){
var _3f88=Math.abs(r.x-p.x);
var _3f89=3;
var i=Math.abs(r.y-p.y);
if(i<=_3f88){
_3f88=i;
_3f89=0;
}
i=Math.abs(r.getBottom()-p.y);
if(i<=_3f88){
_3f88=i;
_3f89=2;
}
i=Math.abs(r.getRight()-p.x);
if(i<_3f88){
_3f88=i;
_3f89=1;
}
return _3f89;
};
ConnectionRouter.prototype.getEndDirection=function(conn){
var p=conn.getEndPoint();
var rect=conn.getTarget().getParent().getBounds();
return this.getDirection(rect,p);
};
ConnectionRouter.prototype.getStartDirection=function(conn){
var p=conn.getStartPoint();
var rect=conn.getSource().getParent().getBounds();
return this.getDirection(rect,p);
};
ConnectionRouter.prototype.route=function(_3f91){
};
NullConnectionRouter=function(){
};
NullConnectionRouter.prototype=new ConnectionRouter;
NullConnectionRouter.prototype.type="NullConnectionRouter";
NullConnectionRouter.prototype.invalidate=function(){
};
NullConnectionRouter.prototype.route=function(_3f6a){
_3f6a.addPoint(_3f6a.getStartPoint());
_3f6a.addPoint(_3f6a.getEndPoint());
};
ManhattanConnectionRouter=function(){
this.MINDIST=20;
};
ManhattanConnectionRouter.prototype=new ConnectionRouter;
ManhattanConnectionRouter.prototype.type="ManhattanConnectionRouter";
ManhattanConnectionRouter.prototype.route=function(conn){
var _3ba8=conn.getStartPoint();
var _3ba9=this.getStartDirection(conn);
var toPt=conn.getEndPoint();
var toDir=this.getEndDirection(conn);
this._route(conn,toPt,toDir,_3ba8,_3ba9);
};
ManhattanConnectionRouter.prototype._route=function(conn,_3bad,_3bae,toPt,toDir){
var TOL=0.1;
var _3bb2=0.01;
var UP=0;
var RIGHT=1;
var DOWN=2;
var LEFT=3;
var xDiff=_3bad.x-toPt.x;
var yDiff=_3bad.y-toPt.y;
var point;
var dir;
if(((xDiff*xDiff)<(_3bb2))&&((yDiff*yDiff)<(_3bb2))){
conn.addPoint(new Point(toPt.x,toPt.y));
return;
}
if(_3bae==LEFT){
if((xDiff>0)&&((yDiff*yDiff)<TOL)&&(toDir==RIGHT)){
point=toPt;
dir=toDir;
}else{
if(xDiff<0){
point=new Point(_3bad.x-this.MINDIST,_3bad.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_3bad.y);
}else{
if(_3bae==toDir){
var pos=Math.min(_3bad.x,toPt.x)-this.MINDIST;
point=new Point(pos,_3bad.y);
}else{
point=new Point(_3bad.x-(xDiff/2),_3bad.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_3bae==RIGHT){
if((xDiff<0)&&((yDiff*yDiff)<TOL)&&(toDir==LEFT)){
point=toPt;
dir=toDir;
}else{
if(xDiff>0){
point=new Point(_3bad.x+this.MINDIST,_3bad.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_3bad.y);
}else{
if(_3bae==toDir){
var pos=Math.max(_3bad.x,toPt.x)+this.MINDIST;
point=new Point(pos,_3bad.y);
}else{
point=new Point(_3bad.x-(xDiff/2),_3bad.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_3bae==DOWN){
if(((xDiff*xDiff)<TOL)&&(yDiff<0)&&(toDir==UP)){
point=toPt;
dir=toDir;
}else{
if(yDiff>0){
point=new Point(_3bad.x,_3bad.y+this.MINDIST);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_3bad.x,toPt.y);
}else{
if(_3bae==toDir){
var pos=Math.max(_3bad.y,toPt.y)+this.MINDIST;
point=new Point(_3bad.x,pos);
}else{
point=new Point(_3bad.x,_3bad.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}else{
if(_3bae==UP){
if(((xDiff*xDiff)<TOL)&&(yDiff>0)&&(toDir==DOWN)){
point=toPt;
dir=toDir;
}else{
if(yDiff<0){
point=new Point(_3bad.x,_3bad.y-this.MINDIST);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_3bad.x,toPt.y);
}else{
if(_3bae==toDir){
var pos=Math.min(_3bad.y,toPt.y)-this.MINDIST;
point=new Point(_3bad.x,pos);
}else{
point=new Point(_3bad.x,_3bad.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}
}
}
}
this._route(conn,point,dir,toPt,toDir);
conn.addPoint(_3bad);
};
BezierConnectionRouter=function(_354a){
if(!_354a){
this.cheapRouter=new ManhattanConnectionRouter();
}else{
this.cheapRouter=null;
}
this.iteration=5;
};
BezierConnectionRouter.prototype=new ConnectionRouter;
BezierConnectionRouter.prototype.type="BezierConnectionRouter";
BezierConnectionRouter.prototype.drawBezier=function(_354b,_354c,t,iter){
var n=_354b.length-1;
var q=new Array();
var _3551=n+1;
for(var i=0;i<_3551;i++){
q[i]=new Array();
q[i][0]=_354b[i];
}
for(var j=1;j<=n;j++){
for(var i=0;i<=(n-j);i++){
q[i][j]=new Point((1-t)*q[i][j-1].x+t*q[i+1][j-1].x,(1-t)*q[i][j-1].y+t*q[i+1][j-1].y);
}
}
var c1=new Array();
var c2=new Array();
for(var i=0;i<n+1;i++){
c1[i]=q[0][i];
c2[i]=q[i][n-i];
}
if(iter>=0){
this.drawBezier(c1,_354c,t,--iter);
this.drawBezier(c2,_354c,t,--iter);
}else{
for(var i=0;i<n;i++){
_354c.push(q[i][n-i]);
}
}
};
BezierConnectionRouter.prototype.route=function(conn){
if(this.cheapRouter!=null&&(conn.getSource().getParent().isMoving==true||conn.getTarget().getParent().isMoving==true)){
this.cheapRouter.route(conn);
return;
}
var _3557=new Array();
var _3558=conn.getStartPoint();
var toPt=conn.getEndPoint();
this._route(_3557,conn,toPt,this.getEndDirection(conn),_3558,this.getStartDirection(conn));
var _355a=new Array();
this.drawBezier(_3557,_355a,0.5,this.iteration);
for(var i=0;i<_355a.length;i++){
conn.addPoint(_355a[i]);
}
conn.addPoint(toPt);
};
BezierConnectionRouter.prototype._route=function(_355c,conn,_355e,_355f,toPt,toDir){
var TOL=0.1;
var _3563=0.01;
var _3564=90;
var UP=0;
var RIGHT=1;
var DOWN=2;
var LEFT=3;
var xDiff=_355e.x-toPt.x;
var yDiff=_355e.y-toPt.y;
var point;
var dir;
if(((xDiff*xDiff)<(_3563))&&((yDiff*yDiff)<(_3563))){
_355c.push(new Point(toPt.x,toPt.y));
return;
}
if(_355f==LEFT){
if((xDiff>0)&&((yDiff*yDiff)<TOL)&&(toDir==RIGHT)){
point=toPt;
dir=toDir;
}else{
if(xDiff<0){
point=new Point(_355e.x-_3564,_355e.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_355e.y);
}else{
if(_355f==toDir){
var pos=Math.min(_355e.x,toPt.x)-_3564;
point=new Point(pos,_355e.y);
}else{
point=new Point(_355e.x-(xDiff/2),_355e.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_355f==RIGHT){
if((xDiff<0)&&((yDiff*yDiff)<TOL)&&(toDir==LEFT)){
point=toPt;
dir=toDir;
}else{
if(xDiff>0){
point=new Point(_355e.x+_3564,_355e.y);
}else{
if(((yDiff>0)&&(toDir==DOWN))||((yDiff<0)&&(toDir==UP))){
point=new Point(toPt.x,_355e.y);
}else{
if(_355f==toDir){
var pos=Math.max(_355e.x,toPt.x)+_3564;
point=new Point(pos,_355e.y);
}else{
point=new Point(_355e.x-(xDiff/2),_355e.y);
}
}
}
if(yDiff>0){
dir=UP;
}else{
dir=DOWN;
}
}
}else{
if(_355f==DOWN){
if(((xDiff*xDiff)<TOL)&&(yDiff<0)&&(toDir==UP)){
point=toPt;
dir=toDir;
}else{
if(yDiff>0){
point=new Point(_355e.x,_355e.y+_3564);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_355e.x,toPt.y);
}else{
if(_355f==toDir){
var pos=Math.max(_355e.y,toPt.y)+_3564;
point=new Point(_355e.x,pos);
}else{
point=new Point(_355e.x,_355e.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}else{
if(_355f==UP){
if(((xDiff*xDiff)<TOL)&&(yDiff>0)&&(toDir==DOWN)){
point=toPt;
dir=toDir;
}else{
if(yDiff<0){
point=new Point(_355e.x,_355e.y-_3564);
}else{
if(((xDiff>0)&&(toDir==RIGHT))||((xDiff<0)&&(toDir==LEFT))){
point=new Point(_355e.x,toPt.y);
}else{
if(_355f==toDir){
var pos=Math.min(_355e.y,toPt.y)-_3564;
point=new Point(_355e.x,pos);
}else{
point=new Point(_355e.x,_355e.y-(yDiff/2));
}
}
}
if(xDiff>0){
dir=LEFT;
}else{
dir=RIGHT;
}
}
}
}
}
}
this._route(_355c,conn,point,dir,toPt,toDir);
_355c.push(_355e);
};
FanConnectionRouter=function(){
};
FanConnectionRouter.prototype=new NullConnectionRouter;
FanConnectionRouter.prototype.type="FanConnectionRouter";
FanConnectionRouter.prototype.route=function(conn){
var _40c7=conn.getStartPoint();
var toPt=conn.getEndPoint();
var lines=conn.getSource().getConnections();
var _40ca=new ArrayList();
var index=0;
for(var i=0;i<lines.getSize();i++){
var _40cd=lines.get(i);
if(_40cd.getTarget()==conn.getTarget()||_40cd.getSource()==conn.getTarget()){
_40ca.add(_40cd);
if(conn==_40cd){
index=_40ca.getSize();
}
}
}
if(_40ca.getSize()>1){
this.routeCollision(conn,index);
}else{
NullConnectionRouter.prototype.route.call(this,conn);
}
};
FanConnectionRouter.prototype.routeNormal=function(conn){
conn.addPoint(conn.getStartPoint());
conn.addPoint(conn.getEndPoint());
};
FanConnectionRouter.prototype.routeCollision=function(conn,index){
var start=conn.getStartPoint();
var end=conn.getEndPoint();
conn.addPoint(start);
var _40d3=10;
var _40d4=new Point((end.x+start.x)/2,(end.y+start.y)/2);
var _40d5=end.getPosition(start);
var ray;
if(_40d5==PositionConstants.SOUTH||_40d5==PositionConstants.EAST){
ray=new Point(end.x-start.x,end.y-start.y);
}else{
ray=new Point(start.x-end.x,start.y-end.y);
}
var _40d7=Math.sqrt(ray.x*ray.x+ray.y*ray.y);
var _40d8=_40d3*ray.x/_40d7;
var _40d9=_40d3*ray.y/_40d7;
var _40da;
if(index%2==0){
_40da=new Point(_40d4.x+(index/2)*(-1*_40d9),_40d4.y+(index/2)*_40d8);
}else{
_40da=new Point(_40d4.x+(index/2)*_40d9,_40d4.y+(index/2)*(-1*_40d8));
}
conn.addPoint(_40da);
conn.addPoint(end);
};
Graphics=function(_3a61,_3a62,_3a63){
this.jsGraphics=_3a61;
this.xt=_3a63.x;
this.yt=_3a63.y;
this.radian=_3a62*Math.PI/180;
this.sinRadian=Math.sin(this.radian);
this.cosRadian=Math.cos(this.radian);
};
Graphics.prototype.setStroke=function(x){
this.jsGraphics.setStroke(x);
};
Graphics.prototype.drawLine=function(x1,y1,x2,y2){
var _x1=this.xt+x1*this.cosRadian-y1*this.sinRadian;
var _y1=this.yt+x1*this.sinRadian+y1*this.cosRadian;
var _x2=this.xt+x2*this.cosRadian-y2*this.sinRadian;
var _y2=this.yt+x2*this.sinRadian+y2*this.cosRadian;
this.jsGraphics.drawLine(_x1,_y1,_x2,_y2);
};
Graphics.prototype.fillRect=function(x,y,w,h){
var x1=this.xt+x*this.cosRadian-y*this.sinRadian;
var y1=this.yt+x*this.sinRadian+y*this.cosRadian;
var x2=this.xt+(x+w)*this.cosRadian-y*this.sinRadian;
var y2=this.yt+(x+w)*this.sinRadian+y*this.cosRadian;
var x3=this.xt+(x+w)*this.cosRadian-(y+h)*this.sinRadian;
var y3=this.yt+(x+w)*this.sinRadian+(y+h)*this.cosRadian;
var x4=this.xt+x*this.cosRadian-(y+h)*this.sinRadian;
var y4=this.yt+x*this.sinRadian+(y+h)*this.cosRadian;
this.jsGraphics.fillPolygon([x1,x2,x3,x4],[y1,y2,y3,y4]);
};
Graphics.prototype.fillPolygon=function(_3a79,_3a7a){
var rotX=new Array();
var rotY=new Array();
for(var i=0;i<_3a79.length;i++){
rotX[i]=this.xt+_3a79[i]*this.cosRadian-_3a7a[i]*this.sinRadian;
rotY[i]=this.yt+_3a79[i]*this.sinRadian+_3a7a[i]*this.cosRadian;
}
this.jsGraphics.fillPolygon(rotX,rotY);
};
Graphics.prototype.setColor=function(color){
this.jsGraphics.setColor(color.getHTMLStyle());
};
Graphics.prototype.drawPolygon=function(_3a7f,_3a80){
var rotX=new Array();
var rotY=new Array();
for(var i=0;i<_3a7f.length;i++){
rotX[i]=this.xt+_3a7f[i]*this.cosRadian-_3a80[i]*this.sinRadian;
rotY[i]=this.yt+_3a7f[i]*this.sinRadian+_3a80[i]*this.cosRadian;
}
this.jsGraphics.drawPolygon(rotX,rotY);
};
Connection=function(){
Line.call(this);
this.sourcePort=null;
this.targetPort=null;
this.sourceDecorator=null;
this.targetDecorator=null;
this.sourceAnchor=new ConnectionAnchor();
this.targetAnchor=new ConnectionAnchor();
this.router=Connection.defaultRouter;
this.lineSegments=new ArrayList();
this.children=new ArrayList();
this.setColor(new Color(0,0,115));
this.setLineWidth(1);
};
Connection.prototype=new Line;
Connection.defaultRouter=new ManhattanConnectionRouter();
Connection.setDefaultRouter=function(_2e24){
Connection.defaultRouter=_2e24;
};
Connection.prototype.disconnect=function(){
if(this.sourcePort!=null){
this.sourcePort.detachMoveListener(this);
this.fireSourcePortRouteEvent();
}
if(this.targetPort!=null){
this.targetPort.detachMoveListener(this);
this.fireTargetPortRouteEvent();
}
};
Connection.prototype.reconnect=function(){
if(this.sourcePort!=null){
this.sourcePort.attachMoveListener(this);
this.fireSourcePortRouteEvent();
}
if(this.targetPort!=null){
this.targetPort.attachMoveListener(this);
this.fireTargetPortRouteEvent();
}
};
Connection.prototype.isResizeable=function(){
return true;
};
Connection.prototype.addFigure=function(_2e25,_2e26){
var entry=new Object();
entry.figure=_2e25;
entry.locator=_2e26;
this.children.add(entry);
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setSourceDecorator=function(_2e28){
this.sourceDecorator=_2e28;
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setTargetDecorator=function(_2e29){
this.targetDecorator=_2e29;
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setSourceAnchor=function(_2e2a){
this.sourceAnchor=_2e2a;
this.sourceAnchor.setOwner(this.sourcePort);
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setTargetAnchor=function(_2e2b){
this.targetAnchor=_2e2b;
this.targetAnchor.setOwner(this.targetPort);
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.setRouter=function(_2e2c){
if(_2e2c!=null){
this.router=_2e2c;
}else{
this.router=new NullConnectionRouter();
}
if(this.graphics!=null){
this.paint();
}
};
Connection.prototype.getRouter=function(){
return this.router;
};
Connection.prototype.paint=function(){
for(var i=0;i<this.children.getSize();i++){
var entry=this.children.get(i);
if(entry.isAppended==true){
this.html.removeChild(entry.figure.getHTMLElement());
}
entry.isAppended=false;
}
if(this.graphics==null){
this.graphics=new jsGraphics(this.id);
}else{
this.graphics.clear();
}
this.graphics.setStroke(this.stroke);
this.graphics.setColor(this.lineColor.getHTMLStyle());
this.startStroke();
this.router.route(this);
if(this.getSource().getParent().isMoving==false&&this.getTarget().getParent().isMoving==false){
if(this.targetDecorator!=null){
this.targetDecorator.paint(new Graphics(this.graphics,this.getEndAngle(),this.getEndPoint()));
}
if(this.sourceDecorator!=null){
this.sourceDecorator.paint(new Graphics(this.graphics,this.getStartAngle(),this.getStartPoint()));
}
}
this.finishStroke();
for(var i=0;i<this.children.getSize();i++){
var entry=this.children.get(i);
this.html.appendChild(entry.figure.getHTMLElement());
entry.isAppended=true;
entry.locator.relocate(entry.figure);
}
};
Connection.prototype.getStartPoint=function(){
if(this.isMoving==false){
return this.sourceAnchor.getLocation(this.targetAnchor.getReferencePoint());
}else{
return Line.prototype.getStartPoint.call(this);
}
};
Connection.prototype.getEndPoint=function(){
if(this.isMoving==false){
return this.targetAnchor.getLocation(this.sourceAnchor.getReferencePoint());
}else{
return Line.prototype.getEndPoint.call(this);
}
};
Connection.prototype.startStroke=function(){
this.oldPoint=null;
this.lineSegments=new ArrayList();
};
Connection.prototype.finishStroke=function(){
this.graphics.paint();
this.oldPoint=null;
};
Connection.prototype.getPoints=function(){
var _2e2f=new ArrayList();
var line;
for(var i=0;i<this.lineSegments.getSize();i++){
line=this.lineSegments.get(i);
_2e2f.add(line.start);
}
_2e2f.add(line.end);
return _2e2f;
};
Connection.prototype.addPoint=function(p){
p=new Point(parseInt(p.x),parseInt(p.y));
if(this.oldPoint!=null){
this.graphics.drawLine(this.oldPoint.x,this.oldPoint.y,p.x,p.y);
var line=new Object();
line.start=this.oldPoint;
line.end=p;
this.lineSegments.add(line);
}
this.oldPoint=new Object();
this.oldPoint.x=p.x;
this.oldPoint.y=p.y;
};
Connection.prototype.setSource=function(port){
if(this.sourcePort!=null){
this.sourcePort.detachMoveListener(this);
}
this.sourcePort=port;
if(this.sourcePort==null){
return;
}
this.sourceAnchor.setOwner(this.sourcePort);
this.fireSourcePortRouteEvent();
this.sourcePort.attachMoveListener(this);
this.setStartPoint(port.getAbsoluteX(),port.getAbsoluteY());
};
Connection.prototype.getSource=function(){
return this.sourcePort;
};
Connection.prototype.setTarget=function(port){
if(this.targetPort!=null){
this.targetPort.detachMoveListener(this);
}
this.targetPort=port;
if(this.targetPort==null){
return;
}
this.targetAnchor.setOwner(this.targetPort);
this.fireTargetPortRouteEvent();
this.targetPort.attachMoveListener(this);
this.setEndPoint(port.getAbsoluteX(),port.getAbsoluteY());
};
Connection.prototype.getTarget=function(){
return this.targetPort;
};
Connection.prototype.onOtherFigureMoved=function(_2e36){
if(_2e36==this.sourcePort){
this.setStartPoint(this.sourcePort.getAbsoluteX(),this.sourcePort.getAbsoluteY());
}else{
this.setEndPoint(this.targetPort.getAbsoluteX(),this.targetPort.getAbsoluteY());
}
};
Connection.prototype.containsPoint=function(px,py){
for(var i=0;i<this.lineSegments.getSize();i++){
var line=this.lineSegments.get(i);
if(Line.hit(line.start.x,line.start.y,line.end.x,line.end.y,px,py)){
return true;
}
}
return false;
};
Connection.prototype.getStartAngle=function(){
var p1=this.lineSegments.get(0).start;
var p2=this.lineSegments.get(0).end;
if(this.router instanceof BezierConnectionRouter){
p2=this.lineSegments.get(5).end;
}
var _2e3d=Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
var angle=-(180/Math.PI)*Math.asin((p1.y-p2.y)/_2e3d);
if(angle<0){
if(p2.x<p1.x){
angle=Math.abs(angle)+180;
}else{
angle=360-Math.abs(angle);
}
}else{
if(p2.x<p1.x){
angle=180-angle;
}
}
return angle;
};
Connection.prototype.getEndAngle=function(){
var p1=this.lineSegments.get(this.lineSegments.getSize()-1).end;
var p2=this.lineSegments.get(this.lineSegments.getSize()-1).start;
if(this.router instanceof BezierConnectionRouter){
p2=this.lineSegments.get(this.lineSegments.getSize()-5).end;
}
var _2e41=Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
var angle=-(180/Math.PI)*Math.asin((p1.y-p2.y)/_2e41);
if(angle<0){
if(p2.x<p1.x){
angle=Math.abs(angle)+180;
}else{
angle=360-Math.abs(angle);
}
}else{
if(p2.x<p1.x){
angle=180-angle;
}
}
return angle;
};
Connection.prototype.fireSourcePortRouteEvent=function(){
var _2e43=this.sourcePort.getConnections();
for(var i=0;i<_2e43.getSize();i++){
_2e43.get(i).paint();
}
};
Connection.prototype.fireTargetPortRouteEvent=function(){
var _2e45=this.targetPort.getConnections();
for(var i=0;i<_2e45.getSize();i++){
_2e45.get(i).paint();
}
};
ConnectionAnchor=function(owner){
this.owner=owner;
};
ConnectionAnchor.prototype.type="ConnectionAnchor";
ConnectionAnchor.prototype.getLocation=function(_40c2){
return this.getReferencePoint();
};
ConnectionAnchor.prototype.getOwner=function(){
return this.owner;
};
ConnectionAnchor.prototype.setOwner=function(owner){
this.owner=owner;
};
ConnectionAnchor.prototype.getBox=function(){
return this.getOwner().getAbsoluteBounds();
};
ConnectionAnchor.prototype.getReferencePoint=function(){
if(this.getOwner()==null){
return null;
}else{
return this.getOwner().getAbsolutePosition();
}
};
ChopboxConnectionAnchor=function(owner){
ConnectionAnchor.call(this,owner);
};
ChopboxConnectionAnchor.prototype=new ConnectionAnchor;
ChopboxConnectionAnchor.prototype.type="ChopboxConnectionAnchor";
ChopboxConnectionAnchor.prototype.getLocation=function(_3854){
var r=new Dimension();
r.setBounds(this.getBox());
r.translate(-1,-1);
r.resize(1,1);
var _3856=r.x+r.w/2;
var _3857=r.y+r.h/2;
if(r.isEmpty()||(_3854.x==_3856&&_3854.y==_3857)){
return new Point(_3856,_3857);
}
var dx=_3854.x-_3856;
var dy=_3854.y-_3857;
var scale=0.5/Math.max(Math.abs(dx)/r.w,Math.abs(dy)/r.h);
dx*=scale;
dy*=scale;
_3856+=dx;
_3857+=dy;
return new Point(Math.round(_3856),Math.round(_3857));
};
ChopboxConnectionAnchor.prototype.getBox=function(){
return this.getOwner().getParent().getBounds();
};
ChopboxConnectionAnchor.prototype.getReferencePoint=function(){
return this.getBox().getCenter();
};
ConnectionDecorator=function(){
this.color=new Color(0,0,0);
this.backgroundColor=new Color(250,250,250);
};
ConnectionDecorator.prototype.type="ConnectionDecorator";
ConnectionDecorator.prototype.paint=function(g){
};
ConnectionDecorator.prototype.setColor=function(c){
this.color=c;
};
ConnectionDecorator.prototype.setBackgroundColor=function(c){
this.backgroundColor=c;
};
ArrowConnectionDecorator=function(){
};
ArrowConnectionDecorator.prototype=new ConnectionDecorator;
ArrowConnectionDecorator.prototype.type="ArrowConnectionDecorator";
ArrowConnectionDecorator.prototype.paint=function(g){
if(this.backgroundColor!=null){
g.setColor(this.backgroundColor);
g.fillPolygon([1,10,10,1],[0,5,-5,0]);
}
g.setColor(this.color);
g.setStroke(1);
g.drawPolygon([1,10,10,1],[0,5,-5,0]);
g.fillPolygon([1,10,10,1],[0,5,-5,0]);
};
CompartmentFigure=function(){
Node.call(this);
this.children=new ArrayList();
this.setBorder(new LineBorder(1));
this.dropable=new DropTarget(this.html);
this.dropable.node=this;
this.dropable.addEventListener("figureenter",function(_4072){
_4072.target.node.onFigureEnter(_4072.relatedTarget.node);
});
this.dropable.addEventListener("figureleave",function(_4073){
_4073.target.node.onFigureLeave(_4073.relatedTarget.node);
});
this.dropable.addEventListener("figuredrop",function(_4074){
_4074.target.node.onFigureDrop(_4074.relatedTarget.node);
});
};
CompartmentFigure.prototype=new Node;
CompartmentFigure.prototype.type="CompartmentFigure";
CompartmentFigure.prototype.onFigureEnter=function(_4075){
};
CompartmentFigure.prototype.onFigureLeave=function(_4076){
};
CompartmentFigure.prototype.onFigureDrop=function(_4077){
};
CompartmentFigure.prototype.getChildren=function(){
return this.children;
};
CompartmentFigure.prototype.addChild=function(_4078){
_4078.setZOrder(this.getZOrder()+1);
_4078.setParent(this);
this.children.add(_4078);
};
CompartmentFigure.prototype.removeChild=function(_4079){
_4079.setParent(null);
this.children.remove(_4079);
};
CompartmentFigure.prototype.setZOrder=function(index){
Node.prototype.setZOrder.call(this,index);
for(var i=0;i<this.children.getSize();i++){
this.children.get(i).setZOrder(index+1);
}
};
CompartmentFigure.prototype.setPosition=function(xPos,yPos){
var oldX=this.getX();
var oldY=this.getY();
Node.prototype.setPosition.call(this,xPos,yPos);
for(var i=0;i<this.children.getSize();i++){
var child=this.children.get(i);
child.setPosition(child.getX()+this.getX()-oldX,child.getY()+this.getY()-oldY);
}
};
CompartmentFigure.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Node.prototype.onDrag.call(this);
for(var i=0;i<this.children.getSize();i++){
var child=this.children.get(i);
child.setPosition(child.getX()+this.getX()-oldX,child.getY()+this.getY()-oldY);
}
};
Document=function(_3a3b){
this.canvas=_3a3b;
};
Document.prototype.getFigures=function(){
var _3a3c=new ArrayList();
var _3a3d=this.canvas.figures;
var _3a3e=this.canvas.dialogs;
for(var i=0;i<_3a3d.getSize();i++){
var _3a40=_3a3d.get(i);
if(_3a3e.indexOf(_3a40)==-1&&_3a40.getParent()==null&&!(_3a40 instanceof Window)){
_3a3c.add(_3a40);
}
}
return _3a3c;
};
Document.prototype.getFigure=function(id){
return this.canvas.getFigure(id);
};
Document.prototype.getLines=function(){
return this.canvas.getLines();
};
Annotation=function(msg){
this.msg=msg;
this.color=new Color(0,0,0);
this.bgColor=new Color(241,241,121);
this.fontSize=10;
this.textNode=null;
Figure.call(this);
};
Annotation.prototype=new Figure;
Annotation.prototype.type="Annotation";
Annotation.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.color=this.color.getHTMLStyle();
item.style.backgroundColor=this.bgColor.getHTMLStyle();
item.style.fontSize=this.fontSize+"pt";
item.style.width="auto";
item.style.height="auto";
item.style.margin="0px";
item.style.padding="0px";
item.onselectstart=function(){
return false;
};
item.unselectable="on";
item.style.MozUserSelect="none";
item.style.cursor="default";
this.textNode=document.createTextNode(this.msg);
item.appendChild(this.textNode);
this.disableTextSelection(item);
return item;
};
Annotation.prototype.onDoubleClick=function(){
var _409d=new AnnotationDialog(this);
this.workflow.showDialog(_409d);
};
Annotation.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
}
};
Annotation.prototype.getBackgroundColor=function(){
return this.bgColor;
};
Annotation.prototype.setFontSize=function(size){
this.fontSize=size;
this.html.style.fontSize=this.fontSize+"pt";
};
Annotation.prototype.getText=function(){
return this.msg;
};
Annotation.prototype.setText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createTextNode(this.msg);
this.html.appendChild(this.textNode);
};
Annotation.prototype.setStyledText=function(text){
this.msg=text;
this.html.removeChild(this.textNode);
this.textNode=document.createElement("div");
this.textNode.innerHTML=text;
this.html.appendChild(this.textNode);
};
ResizeHandle=function(_2d2f,type){
Rectangle.call(this,5,5);
this.type=type;
var _2d31=this.getWidth();
var _2d32=_2d31/2;
switch(this.type){
case 1:
this.setSnapToGridAnchor(new Point(_2d31,_2d31));
break;
case 2:
this.setSnapToGridAnchor(new Point(_2d32,_2d31));
break;
case 3:
this.setSnapToGridAnchor(new Point(0,_2d31));
break;
case 4:
this.setSnapToGridAnchor(new Point(0,_2d32));
break;
case 5:
this.setSnapToGridAnchor(new Point(0,0));
break;
case 6:
this.setSnapToGridAnchor(new Point(_2d32,0));
break;
case 7:
this.setSnapToGridAnchor(new Point(_2d31,0));
break;
case 8:
this.setSnapToGridAnchor(new Point(_2d31,_2d32));
break;
}
this.setBackgroundColor(new Color(0,255,0));
this.setWorkflow(_2d2f);
this.setZOrder(10000);
};
ResizeHandle.prototype=new Rectangle;
ResizeHandle.prototype.type="ResizeHandle";
ResizeHandle.prototype.getSnapToDirection=function(){
switch(this.type){
case 1:
return SnapToHelper.NORTH_WEST;
case 2:
return SnapToHelper.NORTH;
case 3:
return SnapToHelper.NORTH_EAST;
case 4:
return SnapToHelper.EAST;
case 5:
return SnapToHelper.SOUTH_EAST;
case 6:
return SnapToHelper.SOUTH;
case 7:
return SnapToHelper.SOUTH_WEST;
case 8:
return SnapToHelper.WEST;
}
};
ResizeHandle.prototype.onDragend=function(){
if(this.commandMove==null){
return;
}
var _2d33=this.workflow.currentSelection;
this.commandMove.setPosition(_2d33.getX(),_2d33.getY());
this.commandResize.setDimension(_2d33.getWidth(),_2d33.getHeight());
this.workflow.getCommandStack().execute(this.commandResize);
this.workflow.getCommandStack().execute(this.commandMove);
this.commandMove=null;
this.commandResize=null;
this.workflow.hideSnapToHelperLines();
};
ResizeHandle.prototype.setPosition=function(xPos,yPos){
this.x=xPos;
this.y=yPos;
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
};
ResizeHandle.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
var _2d38=this.workflow.currentSelection;
this.commandMove=new CommandMove(_2d38,_2d38.getX(),_2d38.getY());
this.commandResize=new CommandResize(_2d38,_2d38.getWidth(),_2d38.getHeight());
return true;
};
ResizeHandle.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Rectangle.prototype.onDrag.call(this);
var diffX=oldX-this.getX();
var diffY=oldY-this.getY();
var _2d3d=this.workflow.currentSelection.getX();
var _2d3e=this.workflow.currentSelection.getY();
var _2d3f=this.workflow.currentSelection.getWidth();
var _2d40=this.workflow.currentSelection.getHeight();
switch(this.type){
case 1:
this.workflow.currentSelection.setPosition(_2d3d-diffX,_2d3e-diffY);
this.workflow.currentSelection.setDimension(_2d3f+diffX,_2d40+diffY);
break;
case 2:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e-diffY);
this.workflow.currentSelection.setDimension(_2d3f,_2d40+diffY);
break;
case 3:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e-diffY);
this.workflow.currentSelection.setDimension(_2d3f-diffX,_2d40+diffY);
break;
case 4:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f-diffX,_2d40);
break;
case 5:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f-diffX,_2d40-diffY);
break;
case 6:
this.workflow.currentSelection.setPosition(_2d3d,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f,_2d40-diffY);
break;
case 7:
this.workflow.currentSelection.setPosition(_2d3d-diffX,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f+diffX,_2d40-diffY);
break;
case 8:
this.workflow.currentSelection.setPosition(_2d3d-diffX,_2d3e);
this.workflow.currentSelection.setDimension(_2d3f+diffX,_2d40);
break;
}
this.workflow.moveResizeHandles(this.workflow.getCurrentSelection());
};
ResizeHandle.prototype.setCanDrag=function(flag){
Rectangle.prototype.setCanDrag.call(this,flag);
if(!flag){
this.html.style.cursor="";
return;
}
switch(this.type){
case 1:
this.html.style.cursor="nw-resize";
break;
case 2:
this.html.style.cursor="s-resize";
break;
case 3:
this.html.style.cursor="ne-resize";
break;
case 4:
this.html.style.cursor="w-resize";
break;
case 5:
this.html.style.cursor="se-resize";
break;
case 6:
this.html.style.cursor="n-resize";
break;
case 7:
this.html.style.cursor="sw-resize";
break;
case 8:
this.html.style.cursor="e-resize";
break;
}
};
ResizeHandle.prototype.onKeyDown=function(_2d42,ctrl){
this.workflow.onKeyDown(_2d42,ctrl);
};
ResizeHandle.prototype.fireMoveEvent=function(){
};
LineStartResizeHandle=function(_40f9){
Rectangle.call(this);
this.setDimension(10,10);
this.setBackgroundColor(new Color(0,255,0));
this.setWorkflow(_40f9);
this.setZOrder(10000);
};
LineStartResizeHandle.prototype=new Rectangle;
LineStartResizeHandle.prototype.type="LineStartResizeHandle";
LineStartResizeHandle.prototype.onDragend=function(){
var line=this.workflow.currentSelection;
if(line instanceof Connection){
var start=line.sourceAnchor.getLocation(line.targetAnchor.getReferencePoint());
line.setStartPoint(start.x,start.y);
this.getWorkflow().showLineResizeHandles(line);
line.setRouter(line.oldRouter);
}else{
if(this.command==null){
return;
}
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command.setEndPoints(x1,y1,x2,y2);
this.getWorkflow().getCommandStack().execute(this.command);
this.command=null;
}
};
LineStartResizeHandle.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
var line=this.workflow.currentSelection;
if(line instanceof Connection){
this.command=new CommandReconnect(line);
line.oldRouter=line.getRouter();
line.setRouter(new NullConnectionRouter());
}else{
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command=new CommandMoveLine(line,x1,y1,x2,y2);
}
return true;
};
LineStartResizeHandle.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Rectangle.prototype.onDrag.call(this);
var diffX=oldX-this.getX();
var diffY=oldY-this.getY();
var _410b=this.workflow.currentSelection.getStartPoint();
var line=this.workflow.currentSelection;
line.setStartPoint(_410b.x-diffX,_410b.y-diffY);
line.isMoving=true;
};
LineStartResizeHandle.prototype.onDrop=function(_410d){
var line=this.workflow.currentSelection;
line.isMoving=false;
if(line instanceof Connection){
this.command.setNewPorts(_410d,line.getTarget());
this.getWorkflow().getCommandStack().execute(this.command);
}
this.command=null;
};
LineStartResizeHandle.prototype.onKeyDown=function(_410f,ctrl){
if(this.workflow!=null){
this.workflow.onKeyDown(_410f,ctrl);
}
};
LineStartResizeHandle.prototype.fireMoveEvent=function(){
};
LineEndResizeHandle=function(_3f2a){
Rectangle.call(this);
this.setDimension(10,10);
this.setBackgroundColor(new Color(0,255,0));
this.setWorkflow(_3f2a);
this.setZOrder(10000);
};
LineEndResizeHandle.prototype=new Rectangle;
LineEndResizeHandle.prototype.type="LineEndResizeHandle";
LineEndResizeHandle.prototype.onDragend=function(){
var line=this.workflow.currentSelection;
if(line instanceof Connection){
var end=line.targetAnchor.getLocation(line.sourceAnchor.getReferencePoint());
line.setEndPoint(end.x,end.y);
this.getWorkflow().showLineResizeHandles(line);
line.setRouter(line.oldRouter);
}else{
if(this.command==null){
return;
}
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command.setEndPoints(x1,y1,x2,y2);
this.workflow.getCommandStack().execute(this.command);
this.command=null;
}
};
LineEndResizeHandle.prototype.onDragstart=function(x,y){
if(!this.canDrag){
return false;
}
var line=this.workflow.currentSelection;
if(line instanceof Connection){
this.command=new CommandReconnect(line);
line.oldRouter=line.getRouter();
line.setRouter(new NullConnectionRouter());
}else{
var x1=line.getStartX();
var y1=line.getStartY();
var x2=line.getEndX();
var y2=line.getEndY();
this.command=new CommandMoveLine(line,x1,y1,x2,y2);
}
return true;
};
LineEndResizeHandle.prototype.onDrag=function(){
var oldX=this.getX();
var oldY=this.getY();
Rectangle.prototype.onDrag.call(this);
var diffX=oldX-this.getX();
var diffY=oldY-this.getY();
var _3f3c=this.workflow.currentSelection.getEndPoint();
var line=this.workflow.currentSelection;
line.setEndPoint(_3f3c.x-diffX,_3f3c.y-diffY);
line.isMoving=true;
};
LineEndResizeHandle.prototype.onDrop=function(_3f3e){
var line=this.workflow.currentSelection;
line.isMoving=false;
if(line instanceof Connection){
this.command.setNewPorts(line.getSource(),_3f3e);
this.getWorkflow().getCommandStack().execute(this.command);
}
this.command=null;
};
LineEndResizeHandle.prototype.onKeyDown=function(_3f40){
if(this.workflow!=null){
this.workflow.onKeyDown(_3f40);
}
};
LineEndResizeHandle.prototype.fireMoveEvent=function(){
};
Canvas=function(_3e59){
if(_3e59){
this.construct(_3e59);
}
this.enableSmoothFigureHandling=false;
this.canvasLines=new ArrayList();
};
Canvas.prototype.type="Canvas";
Canvas.prototype.construct=function(_3e5a){
this.canvasId=_3e5a;
this.html=document.getElementById(this.canvasId);
this.scrollArea=document.body.parentNode;
};
Canvas.prototype.setViewPort=function(divId){
this.scrollArea=document.getElementById(divId);
};
Canvas.prototype.addFigure=function(_3e5c,xPos,yPos,_3e5f){
if(this.enableSmoothFigureHandling==true){
if(_3e5c.timer<=0){
_3e5c.setAlpha(0.001);
}
var _3e60=_3e5c;
var _3e61=function(){
if(_3e60.alpha<1){
_3e60.setAlpha(Math.min(1,_3e60.alpha+0.05));
}else{
window.clearInterval(_3e60.timer);
_3e60.timer=-1;
}
};
if(_3e60.timer>0){
window.clearInterval(_3e60.timer);
}
_3e60.timer=window.setInterval(_3e61,30);
}
_3e5c.setCanvas(this);
if(xPos&&yPos){
_3e5c.setPosition(xPos,yPos);
}
if(_3e5c instanceof Line){
this.canvasLines.add(_3e5c);
this.html.appendChild(_3e5c.getHTMLElement());
}else{
var obj=this.canvasLines.getFirstElement();
if(obj==null){
this.html.appendChild(_3e5c.getHTMLElement());
}else{
this.html.insertBefore(_3e5c.getHTMLElement(),obj.getHTMLElement());
}
}
if(!_3e5f){
_3e5c.paint();
}
};
Canvas.prototype.removeFigure=function(_3e63){
if(this.enableSmoothFigureHandling==true){
var oThis=this;
var _3e65=_3e63;
var _3e66=function(){
if(_3e65.alpha>0){
_3e65.setAlpha(Math.max(0,_3e65.alpha-0.05));
}else{
window.clearInterval(_3e65.timer);
_3e65.timer=-1;
oThis.html.removeChild(_3e65.html);
_3e65.setCanvas(null);
}
};
if(_3e65.timer>0){
window.clearInterval(_3e65.timer);
}
_3e65.timer=window.setInterval(_3e66,20);
}else{
this.html.removeChild(_3e63.html);
_3e63.setCanvas(null);
}
if(_3e63 instanceof Line){
this.canvasLines.remove(_3e63);
}
};
Canvas.prototype.getEnableSmoothFigureHandling=function(){
return this.enableSmoothFigureHandling;
};
Canvas.prototype.setEnableSmoothFigureHandling=function(flag){
this.enableSmoothFigureHandling=flag;
};
Canvas.prototype.getWidth=function(){
return parseInt(this.html.style.width);
};
Canvas.prototype.getHeight=function(){
return parseInt(this.html.style.height);
};
Canvas.prototype.setBackgroundImage=function(_3e68,_3e69){
if(_3e68!=null){
if(_3e69){
this.html.style.background="transparent url("+_3e68+") ";
}else{
this.html.style.background="transparent url("+_3e68+") no-repeat";
}
}else{
this.html.style.background="transparent";
}
};
Canvas.prototype.getY=function(){
return this.y;
};
Canvas.prototype.getX=function(){
return this.x;
};
Canvas.prototype.getAbsoluteY=function(){
var el=this.html;
var ot=el.offsetTop;
while((el=el.offsetParent)!=null){
ot+=el.offsetTop;
}
return ot;
};
Canvas.prototype.getAbsoluteX=function(){
var el=this.html;
var ol=el.offsetLeft;
while((el=el.offsetParent)!=null){
ol+=el.offsetLeft;
}
return ol;
};
Canvas.prototype.getScrollLeft=function(){
return this.scrollArea.scrollLeft;
};
Canvas.prototype.getScrollTop=function(){
return this.scrollArea.scrollTop;
};
Workflow=function(id){
if(!id){
return;
}
this.gridWidthX=10;
this.gridWidthY=10;
this.snapToGridHelper=null;
this.verticalSnapToHelperLine=null;
this.horizontalSnapToHelperLine=null;
this.figures=new ArrayList();
this.lines=new ArrayList();
this.commonPorts=new ArrayList();
this.dropTargets=new ArrayList();
this.compartments=new ArrayList();
this.selectionListeners=new ArrayList();
this.dialogs=new ArrayList();
this.toolPalette=null;
this.dragging=false;
this.tooltip=null;
this.draggingLine=null;
this.commandStack=new CommandStack();
this.oldScrollPosLeft=0;
this.oldScrollPosTop=0;
this.currentSelection=null;
this.currentMenu=null;
this.connectionLine=new Line();
this.resizeHandleStart=new LineStartResizeHandle(this);
this.resizeHandleEnd=new LineEndResizeHandle(this);
this.resizeHandle1=new ResizeHandle(this,1);
this.resizeHandle2=new ResizeHandle(this,2);
this.resizeHandle3=new ResizeHandle(this,3);
this.resizeHandle4=new ResizeHandle(this,4);
this.resizeHandle5=new ResizeHandle(this,5);
this.resizeHandle6=new ResizeHandle(this,6);
this.resizeHandle7=new ResizeHandle(this,7);
this.resizeHandle8=new ResizeHandle(this,8);
this.resizeHandleHalfWidth=parseInt(this.resizeHandle2.getWidth()/2);
Canvas.call(this,id);
this.setPanning(false);
if(this.html!=null){
this.html.style.backgroundImage="url(grid_10.png)";
oThis=this;
this.html.tabIndex="0";
var _4116=function(){
var _4117=arguments[0]||window.event;
var diffX=_4117.clientX;
var diffY=_4117.clientY;
var _411a=oThis.getScrollLeft();
var _411b=oThis.getScrollTop();
var _411c=oThis.getAbsoluteX();
var _411d=oThis.getAbsoluteY();
if(oThis.getBestFigure(diffX+_411a-_411c,diffY+_411b-_411d)!=null){
return;
}
var line=oThis.getBestLine(diffX+_411a-_411c,diffY+_411b-_411d,null);
if(line!=null){
line.onContextMenu(diffX+_411a-_411c,diffY+_411b-_411d);
}else{
oThis.onContextMenu(diffX+_411a-_411c,diffY+_411b-_411d);
}
};
this.html.oncontextmenu=function(){
return false;
};
var oThis=this;
var _4120=function(event){
var ctrl=event.ctrlKey;
oThis.onKeyDown(event.keyCode,ctrl);
};
var _4123=function(){
var _4124=arguments[0]||window.event;
var diffX=_4124.clientX;
var diffY=_4124.clientY;
var _4127=oThis.getScrollLeft();
var _4128=oThis.getScrollTop();
var _4129=oThis.getAbsoluteX();
var _412a=oThis.getAbsoluteY();
oThis.onMouseDown(diffX+_4127-_4129,diffY+_4128-_412a);
};
var _412b=function(){
var _412c=arguments[0]||window.event;
if(oThis.currentMenu!=null){
oThis.removeFigure(oThis.currentMenu);
oThis.currentMenu=null;
}
if(_412c.button==2){
return;
}
var diffX=_412c.clientX;
var diffY=_412c.clientY;
var _412f=oThis.getScrollLeft();
var _4130=oThis.getScrollTop();
var _4131=oThis.getAbsoluteX();
var _4132=oThis.getAbsoluteY();
oThis.onMouseUp(diffX+_412f-_4131,diffY+_4130-_4132);
};
var _4133=function(){
var _4134=arguments[0]||window.event;
var diffX=_4134.clientX;
var diffY=_4134.clientY;
var _4137=oThis.getScrollLeft();
var _4138=oThis.getScrollTop();
var _4139=oThis.getAbsoluteX();
var _413a=oThis.getAbsoluteY();
oThis.currentMouseX=diffX+_4137-_4139;
oThis.currentMouseY=diffY+_4138-_413a;
var obj=oThis.getBestFigure(oThis.currentMouseX,oThis.currentMouseY);
if(Drag.currentHover!=null&&obj==null){
var _413c=new DragDropEvent();
_413c.initDragDropEvent("mouseleave",false,oThis);
Drag.currentHover.dispatchEvent(_413c);
}else{
var diffX=_4134.clientX;
var diffY=_4134.clientY;
var _4137=oThis.getScrollLeft();
var _4138=oThis.getScrollTop();
var _4139=oThis.getAbsoluteX();
var _413a=oThis.getAbsoluteY();
oThis.onMouseMove(diffX+_4137-_4139,diffY+_4138-_413a);
}
if(obj==null){
Drag.currentHover=null;
}
if(oThis.tooltip!=null){
if(Math.abs(oThis.currentTooltipX-oThis.currentMouseX)>10||Math.abs(oThis.currentTooltipY-oThis.currentMouseY)>10){
oThis.showTooltip(null);
}
}
};
var _413d=function(_413e){
var _413e=arguments[0]||window.event;
var diffX=_413e.clientX;
var diffY=_413e.clientY;
var _4141=oThis.getScrollLeft();
var _4142=oThis.getScrollTop();
var _4143=oThis.getAbsoluteX();
var _4144=oThis.getAbsoluteY();
var line=oThis.getBestLine(diffX+_4141-_4143,diffY+_4142-_4144,null);
if(line!=null){
line.onDoubleClick();
}
};
if(this.html.addEventListener){
this.html.addEventListener("contextmenu",_4116,false);
this.html.addEventListener("mousemove",_4133,false);
this.html.addEventListener("mouseup",_412b,false);
this.html.addEventListener("mousedown",_4123,false);
this.html.addEventListener("keydown",_4120,false);
this.html.addEventListener("dblclick",_413d,false);
}else{
if(this.html.attachEvent){
this.html.attachEvent("oncontextmenu",_4116);
this.html.attachEvent("onmousemove",_4133);
this.html.attachEvent("onmousedown",_4123);
this.html.attachEvent("onmouseup",_412b);
this.html.attachEvent("onkeydown",_4120);
this.html.attachEvent("ondblclick",_413d);
}else{
throw new Error("Open-jACOB Draw2D not supported in this browser.");
}
}
}
};
Workflow.prototype=new Canvas;
Workflow.prototype.type="Workflow";
Workflow.COLOR_GREEN=new Color(0,255,0);
Workflow.prototype.onScroll=function(){
var _4146=this.getScrollLeft();
var _4147=this.getScrollTop();
var _4148=_4146-this.oldScrollPosLeft;
var _4149=_4147-this.oldScrollPosTop;
for(var i=0;i<this.figures.getSize();i++){
var _414b=this.figures.get(i);
if(_414b.hasFixedPosition&&_414b.hasFixedPosition()==true){
_414b.setPosition(_414b.getX()+_4148,_414b.getY()+_4149);
}
}
this.oldScrollPosLeft=_4146;
this.oldScrollPosTop=_4147;
};
Workflow.prototype.setPanning=function(flag){
this.panning=flag;
if(flag){
this.html.style.cursor="move";
}else{
this.html.style.cursor="default";
}
};
Workflow.prototype.scrollTo=function(x,y,fast){
if(fast){
this.scrollArea.scrollLeft=x;
this.scrollArea.scrollTop=y;
}else{
var steps=40;
var xStep=(x-this.getScrollLeft())/steps;
var yStep=(y-this.getScrollTop())/steps;
var oldX=this.getScrollLeft();
var oldY=this.getScrollTop();
for(var i=0;i<steps;i++){
this.scrollArea.scrollLeft=oldX+(xStep*i);
this.scrollArea.scrollTop=oldY+(yStep*i);
}
}
};
Workflow.prototype.showTooltip=function(_4156,_4157){
if(this.tooltip!=null){
this.removeFigure(this.tooltip);
this.tooltip=null;
if(this.tooltipTimer>=0){
window.clearTimeout(this.tooltipTimer);
this.tooltipTimer=-1;
}
}
this.tooltip=_4156;
if(this.tooltip!=null){
this.currentTooltipX=this.currentMouseX;
this.currentTooltipY=this.currentMouseY;
this.addFigure(this.tooltip,this.currentTooltipX+10,this.currentTooltipY+10);
var oThis=this;
var _4159=function(){
oThis.tooltipTimer=-1;
oThis.showTooltip(null);
};
if(_4157==true){
this.tooltipTimer=window.setTimeout(_4159,5000);
}
}
};
Workflow.prototype.showDialog=function(_415a,xPos,yPos){
if(xPos){
this.addFigure(_415a,xPos,yPos);
}else{
this.addFigure(_415a,200,100);
}
this.dialogs.add(_415a);
};
Workflow.prototype.showMenu=function(menu,xPos,yPos){
if(this.menu!=null){
this.html.removeChild(this.menu.getHTMLElement());
this.menu.setWorkflow();
}
this.menu=menu;
if(this.menu!=null){
this.menu.setWorkflow(this);
this.menu.setPosition(xPos,yPos);
this.html.appendChild(this.menu.getHTMLElement());
this.menu.paint();
}
};
Workflow.prototype.onContextMenu=function(x,y){
var menu=this.getContextMenu();
if(menu!=null){
this.showMenu(menu,x,y);
}
};
Workflow.prototype.getContextMenu=function(){
return null;
};
Workflow.prototype.setToolWindow=function(_4163,x,y){
this.toolPalette=_4163;
if(y){
this.addFigure(_4163,x,y);
}else{
this.addFigure(_4163,20,20);
}
this.dialogs.add(_4163);
};
Workflow.prototype.setSnapToGrid=function(flag){
if(flag){
this.snapToGridHelper=new SnapToGrid(this);
}else{
this.snapToGridHelper=null;
}
};
Workflow.prototype.setSnapToGeometry=function(flag){
if(flag){
this.snapToGeometryHelper=new SnapToGeometry(this);
}else{
this.snapToGeometryHelper=null;
}
};
Workflow.prototype.setGridWidth=function(dx,dy){
this.gridWidthX=dx;
this.gridWidthY=dy;
};
Workflow.prototype.addFigure=function(_416a,xPos,yPos){
Canvas.prototype.addFigure.call(this,_416a,xPos,yPos,true);
_416a.setWorkflow(this);
var _416d=this;
if(_416a instanceof CompartmentFigure){
this.compartments.add(_416a);
}
if(_416a instanceof Line){
this.lines.add(_416a);
}else{
this.figures.add(_416a);
_416a.draggable.addEventListener("dragend",function(_416e){
});
_416a.draggable.addEventListener("dragstart",function(_416f){
var _4170=_416d.getFigure(_416f.target.element.id);
if(_4170==null){
return;
}
if(_4170.isSelectable()==false){
return;
}
_416d.showResizeHandles(_4170);
_416d.setCurrentSelection(_4170);
});
_416a.draggable.addEventListener("drag",function(_4171){
var _4172=_416d.getFigure(_4171.target.element.id);
if(_4172==null){
return;
}
if(_4172.isSelectable()==false){
return;
}
_416d.moveResizeHandles(_4172);
});
}
_416a.paint();
this.setDocumentDirty();
};
Workflow.prototype.removeFigure=function(_4173){
Canvas.prototype.removeFigure.call(this,_4173);
this.figures.remove(_4173);
this.lines.remove(_4173);
this.dialogs.remove(_4173);
_4173.setWorkflow(null);
if(_4173 instanceof CompartmentFigure){
this.compartments.remove(_4173);
}
if(_4173 instanceof Connection){
_4173.disconnect();
}
if(this.currentSelection==_4173){
this.setCurrentSelection(null);
}
this.setDocumentDirty();
};
Workflow.prototype.moveFront=function(_4174){
this.html.removeChild(_4174.getHTMLElement());
this.html.appendChild(_4174.getHTMLElement());
};
Workflow.prototype.moveBack=function(_4175){
this.html.removeChild(_4175.getHTMLElement());
this.html.insertBefore(_4175.getHTMLElement(),this.html.firstChild);
};
Workflow.prototype.getBestCompartmentFigure=function(x,y,_4178){
var _4179=null;
for(var i=0;i<this.figures.getSize();i++){
var _417b=this.figures.get(i);
if((_417b instanceof CompartmentFigure)&&_417b.isOver(x,y)==true&&_417b!=_4178){
if(_4179==null){
_4179=_417b;
}else{
if(_4179.getZOrder()<_417b.getZOrder()){
_4179=_417b;
}
}
}
}
return _4179;
};
Workflow.prototype.getBestFigure=function(x,y,_417e){
var _417f=null;
for(var i=0;i<this.figures.getSize();i++){
var _4181=this.figures.get(i);
if(_4181.isOver(x,y)==true&&_4181!=_417e){
if(_417f==null){
_417f=_4181;
}else{
if(_417f.getZOrder()<_4181.getZOrder()){
_417f=_4181;
}
}
}
}
return _417f;
};
Workflow.prototype.getBestLine=function(x,y,_4184){
var _4185=null;
for(var i=0;i<this.lines.getSize();i++){
var line=this.lines.get(i);
if(line.containsPoint(x,y)==true&&line!=_4184){
if(_4185==null){
_4185=line;
}else{
if(_4185.getZOrder()<line.getZOrder()){
_4185=line;
}
}
}
}
return _4185;
};
Workflow.prototype.getFigure=function(id){
for(var i=0;i<this.figures.getSize();i++){
var _418a=this.figures.get(i);
if(_418a.id==id){
return _418a;
}
}
return null;
};
Workflow.prototype.getFigures=function(){
return this.figures;
};
Workflow.prototype.getDocument=function(){
return new Document(this);
};
Workflow.prototype.addSelectionListener=function(w){
this.selectionListeners.add(w);
};
Workflow.prototype.removeSelectionListener=function(w){
this.selectionListeners.remove(w);
};
Workflow.prototype.setCurrentSelection=function(_418d){
if(_418d==null){
this.hideResizeHandles();
this.hideLineResizeHandles();
}
this.currentSelection=_418d;
for(var i=0;i<this.selectionListeners.getSize();i++){
var w=this.selectionListeners.get(i);
if(w!=null&&w.onSelectionChanged){
w.onSelectionChanged(this.currentSelection);
}
}
};
Workflow.prototype.getCurrentSelection=function(){
return this.currentSelection;
};
Workflow.prototype.getLines=function(){
return this.lines;
};
Workflow.prototype.registerPort=function(port){
port.draggable.targets=this.dropTargets;
this.commonPorts.add(port);
this.dropTargets.add(port.dropable);
};
Workflow.prototype.unregisterPort=function(port){
port.draggable.targets=null;
this.commonPorts.remove(port);
this.dropTargets.remove(port.dropable);
};
Workflow.prototype.getCommandStack=function(){
return this.commandStack;
};
Workflow.prototype.showConnectionLine=function(x1,y1,x2,y2){
this.connectionLine.setStartPoint(x1,y1);
this.connectionLine.setEndPoint(x2,y2);
if(this.connectionLine.canvas==null){
Canvas.prototype.addFigure.call(this,this.connectionLine);
}
};
Workflow.prototype.hideConnectionLine=function(){
if(this.connectionLine.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.connectionLine);
}
};
Workflow.prototype.showLineResizeHandles=function(_4196){
var _4197=this.resizeHandleStart.getWidth()/2;
var _4198=this.resizeHandleStart.getHeight()/2;
var _4199=_4196.getStartPoint();
var _419a=_4196.getEndPoint();
Canvas.prototype.addFigure.call(this,this.resizeHandleStart,_4199.x-_4197,_4199.y-_4197);
Canvas.prototype.addFigure.call(this,this.resizeHandleEnd,_419a.x-_4197,_419a.y-_4197);
this.resizeHandleStart.setCanDrag(_4196.isResizeable());
this.resizeHandleEnd.setCanDrag(_4196.isResizeable());
if(_4196.isResizeable()){
this.resizeHandleStart.setBackgroundColor(Workflow.COLOR_GREEN);
this.resizeHandleEnd.setBackgroundColor(Workflow.COLOR_GREEN);
this.resizeHandleStart.draggable.targets=this.dropTargets;
this.resizeHandleEnd.draggable.targets=this.dropTargets;
}else{
this.resizeHandleStart.setBackgroundColor(null);
this.resizeHandleEnd.setBackgroundColor(null);
}
};
Workflow.prototype.hideLineResizeHandles=function(){
if(this.resizeHandleStart.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandleStart);
}
if(this.resizeHandleEnd.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandleEnd);
}
};
Workflow.prototype.showResizeHandles=function(_419b){
this.hideLineResizeHandles();
this.hideResizeHandles();
if(this.getEnableSmoothFigureHandling()==true&&this.getCurrentSelection()!=_419b){
this.resizeHandle1.setAlpha(0.01);
this.resizeHandle2.setAlpha(0.01);
this.resizeHandle3.setAlpha(0.01);
this.resizeHandle4.setAlpha(0.01);
this.resizeHandle5.setAlpha(0.01);
this.resizeHandle6.setAlpha(0.01);
this.resizeHandle7.setAlpha(0.01);
this.resizeHandle8.setAlpha(0.01);
}
var _419c=this.resizeHandle1.getWidth();
var _419d=this.resizeHandle1.getHeight();
var _419e=_419b.getHeight();
var _419f=_419b.getWidth();
var xPos=_419b.getX();
var yPos=_419b.getY();
Canvas.prototype.addFigure.call(this,this.resizeHandle1,xPos-_419c,yPos-_419d);
Canvas.prototype.addFigure.call(this,this.resizeHandle3,xPos+_419f,yPos-_419d);
Canvas.prototype.addFigure.call(this,this.resizeHandle5,xPos+_419f,yPos+_419e);
Canvas.prototype.addFigure.call(this,this.resizeHandle7,xPos-_419c,yPos+_419e);
this.moveFront(this.resizeHandle1);
this.moveFront(this.resizeHandle3);
this.moveFront(this.resizeHandle5);
this.moveFront(this.resizeHandle7);
this.resizeHandle1.setCanDrag(_419b.isResizeable());
this.resizeHandle3.setCanDrag(_419b.isResizeable());
this.resizeHandle5.setCanDrag(_419b.isResizeable());
this.resizeHandle7.setCanDrag(_419b.isResizeable());
if(_419b.isResizeable()){
var green=new Color(0,255,0);
this.resizeHandle1.setBackgroundColor(green);
this.resizeHandle3.setBackgroundColor(green);
this.resizeHandle5.setBackgroundColor(green);
this.resizeHandle7.setBackgroundColor(green);
}else{
this.resizeHandle1.setBackgroundColor(null);
this.resizeHandle3.setBackgroundColor(null);
this.resizeHandle5.setBackgroundColor(null);
this.resizeHandle7.setBackgroundColor(null);
}
if(_419b.isStrechable()&&_419b.isResizeable()){
this.resizeHandle2.setCanDrag(_419b.isResizeable());
this.resizeHandle4.setCanDrag(_419b.isResizeable());
this.resizeHandle6.setCanDrag(_419b.isResizeable());
this.resizeHandle8.setCanDrag(_419b.isResizeable());
Canvas.prototype.addFigure.call(this,this.resizeHandle2,xPos+(_419f/2)-this.resizeHandleHalfWidth,yPos-_419d);
Canvas.prototype.addFigure.call(this,this.resizeHandle4,xPos+_419f,yPos+(_419e/2)-(_419d/2));
Canvas.prototype.addFigure.call(this,this.resizeHandle6,xPos+(_419f/2)-this.resizeHandleHalfWidth,yPos+_419e);
Canvas.prototype.addFigure.call(this,this.resizeHandle8,xPos-_419c,yPos+(_419e/2)-(_419d/2));
this.moveFront(this.resizeHandle2);
this.moveFront(this.resizeHandle4);
this.moveFront(this.resizeHandle6);
this.moveFront(this.resizeHandle8);
}
};
Workflow.prototype.hideResizeHandles=function(){
if(this.resizeHandle1.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle1);
}
if(this.resizeHandle2.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle2);
}
if(this.resizeHandle3.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle3);
}
if(this.resizeHandle4.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle4);
}
if(this.resizeHandle5.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle5);
}
if(this.resizeHandle6.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle6);
}
if(this.resizeHandle7.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle7);
}
if(this.resizeHandle8.canvas!=null){
Canvas.prototype.removeFigure.call(this,this.resizeHandle8);
}
};
Workflow.prototype.moveResizeHandles=function(_41a3){
var _41a4=this.resizeHandle1.getWidth();
var _41a5=this.resizeHandle1.getHeight();
var _41a6=_41a3.getHeight();
var _41a7=_41a3.getWidth();
var xPos=_41a3.getX();
var yPos=_41a3.getY();
this.resizeHandle1.setPosition(xPos-_41a4,yPos-_41a5);
this.resizeHandle3.setPosition(xPos+_41a7,yPos-_41a5);
this.resizeHandle5.setPosition(xPos+_41a7,yPos+_41a6);
this.resizeHandle7.setPosition(xPos-_41a4,yPos+_41a6);
if(_41a3.isStrechable()){
this.resizeHandle2.setPosition(xPos+(_41a7/2)-this.resizeHandleHalfWidth,yPos-_41a5);
this.resizeHandle4.setPosition(xPos+_41a7,yPos+(_41a6/2)-(_41a5/2));
this.resizeHandle6.setPosition(xPos+(_41a7/2)-this.resizeHandleHalfWidth,yPos+_41a6);
this.resizeHandle8.setPosition(xPos-_41a4,yPos+(_41a6/2)-(_41a5/2));
}
};
Workflow.prototype.onMouseDown=function(x,y){
this.dragging=true;
this.mouseDownPosX=x;
this.mouseDownPosY=y;
if(this.toolPalette!=null&&this.toolPalette.getActiveTool()!=null){
this.toolPalette.getActiveTool().execute(x,y);
}
this.setCurrentSelection(null);
this.showMenu(null);
var size=this.getLines().getSize();
for(var i=0;i<size;i++){
var line=this.lines.get(i);
if(line.containsPoint(x,y)&&line.isSelectable()){
this.hideResizeHandles();
this.setCurrentSelection(line);
this.showLineResizeHandles(this.currentSelection);
if(line instanceof Line&&!(line instanceof Connection)){
this.draggingLine=line;
}
break;
}
}
};
Workflow.prototype.onMouseUp=function(x,y){
this.dragging=false;
this.draggingLine=null;
};
Workflow.prototype.onMouseMove=function(x,y){
if(this.dragging==true&&this.draggingLine!=null){
var diffX=x-this.mouseDownPosX;
var diffY=y-this.mouseDownPosY;
this.draggingLine.startX=this.draggingLine.getStartX()+diffX;
this.draggingLine.startY=this.draggingLine.getStartY()+diffY;
this.draggingLine.setEndPoint(this.draggingLine.getEndX()+diffX,this.draggingLine.getEndY()+diffY);
this.mouseDownPosX=x;
this.mouseDownPosY=y;
this.showLineResizeHandles(this.currentSelection);
}else{
if(this.dragging==true&&this.panning==true){
var diffX=x-this.mouseDownPosX;
var diffY=y-this.mouseDownPosY;
this.scrollTo(this.getScrollLeft()-diffX,this.getScrollTop()-diffY,true);
this.onScroll();
}
}
};
Workflow.prototype.onKeyDown=function(_41b5,ctrl){
if(_41b5==46&&this.currentSelection!=null&&this.currentSelection.isDeleteable()){
this.commandStack.execute(new CommandDelete(this.currentSelection));
}else{
if(_41b5==90&&ctrl){
this.commandStack.undo();
}else{
if(_41b5==89&&ctrl){
this.commandStack.redo();
}
}
}
};
Workflow.prototype.setDocumentDirty=function(){
for(var i=0;i<this.dialogs.getSize();i++){
var d=this.dialogs.get(i);
if(d!=null&&d.onSetDocumentDirty){
d.onSetDocumentDirty();
}
}
if(this.snapToGeometryHelper!=null){
this.snapToGeometryHelper.onSetDocumentDirty();
}
if(this.snapToGridHelper!=null){
this.snapToGridHelper.onSetDocumentDirty();
}
};
Workflow.prototype.snapToHelper=function(_41b9,pos){
if(this.snapToGeometryHelper!=null){
if(_41b9 instanceof ResizeHandle){
var _41bb=_41b9.getSnapToGridAnchor();
pos.x+=_41bb.x;
pos.y+=_41bb.y;
var _41bc=new Point(pos.x,pos.y);
var _41bd=_41b9.getSnapToDirection();
var _41be=this.snapToGeometryHelper.snapPoint(_41bd,pos,_41bc);
if((_41bd&SnapToHelper.EAST_WEST)&&!(_41be&SnapToHelper.EAST_WEST)){
this.showSnapToHelperLineVertical(_41bc.x);
}else{
this.hideSnapToHelperLineVertical();
}
if((_41bd&SnapToHelper.NORTH_SOUTH)&&!(_41be&SnapToHelper.NORTH_SOUTH)){
this.showSnapToHelperLineHorizontal(_41bc.y);
}else{
this.hideSnapToHelperLineHorizontal();
}
_41bc.x-=_41bb.x;
_41bc.y-=_41bb.y;
return _41bc;
}else{
var _41bf=new Dimension(pos.x,pos.y,_41b9.getWidth(),_41b9.getHeight());
var _41bc=new Dimension(pos.x,pos.y,_41b9.getWidth(),_41b9.getHeight());
var _41bd=SnapToHelper.NSEW;
var _41be=this.snapToGeometryHelper.snapRectangle(_41bf,_41bc);
if((_41bd&SnapToHelper.WEST)&&!(_41be&SnapToHelper.WEST)){
this.showSnapToHelperLineVertical(_41bc.x);
}else{
if((_41bd&SnapToHelper.EAST)&&!(_41be&SnapToHelper.EAST)){
this.showSnapToHelperLineVertical(_41bc.getX()+_41bc.getWidth());
}else{
this.hideSnapToHelperLineVertical();
}
}
if((_41bd&SnapToHelper.NORTH)&&!(_41be&SnapToHelper.NORTH)){
this.showSnapToHelperLineHorizontal(_41bc.y);
}else{
if((_41bd&SnapToHelper.SOUTH)&&!(_41be&SnapToHelper.SOUTH)){
this.showSnapToHelperLineHorizontal(_41bc.getY()+_41bc.getHeight());
}else{
this.hideSnapToHelperLineHorizontal();
}
}
return _41bc.getTopLeft();
}
}else{
if(this.snapToGridHelper!=null){
var _41bb=_41b9.getSnapToGridAnchor();
pos.x=pos.x+_41bb.x;
pos.y=pos.y+_41bb.y;
var _41bc=new Point(pos.x,pos.y);
this.snapToGridHelper.snapPoint(0,pos,_41bc);
_41bc.x=_41bc.x-_41bb.x;
_41bc.y=_41bc.y-_41bb.y;
return _41bc;
}
}
return pos;
};
Workflow.prototype.showSnapToHelperLineHorizontal=function(_41c0){
if(this.horizontalSnapToHelperLine==null){
this.horizontalSnapToHelperLine=new Line();
this.horizontalSnapToHelperLine.setColor(new Color(175,175,255));
this.addFigure(this.horizontalSnapToHelperLine);
}
this.horizontalSnapToHelperLine.setStartPoint(0,_41c0);
this.horizontalSnapToHelperLine.setEndPoint(this.getWidth(),_41c0);
};
Workflow.prototype.showSnapToHelperLineVertical=function(_41c1){
if(this.verticalSnapToHelperLine==null){
this.verticalSnapToHelperLine=new Line();
this.verticalSnapToHelperLine.setColor(new Color(175,175,255));
this.addFigure(this.verticalSnapToHelperLine);
}
this.verticalSnapToHelperLine.setStartPoint(_41c1,0);
this.verticalSnapToHelperLine.setEndPoint(_41c1,this.getHeight());
};
Workflow.prototype.hideSnapToHelperLines=function(){
this.hideSnapToHelperLineHorizontal();
this.hideSnapToHelperLineVertical();
};
Workflow.prototype.hideSnapToHelperLineHorizontal=function(){
if(this.horizontalSnapToHelperLine!=null){
this.removeFigure(this.horizontalSnapToHelperLine);
this.horizontalSnapToHelperLine=null;
}
};
Workflow.prototype.hideSnapToHelperLineVertical=function(){
if(this.verticalSnapToHelperLine!=null){
this.removeFigure(this.verticalSnapToHelperLine);
this.verticalSnapToHelperLine=null;
}
};
Window=function(title){
this.title=title;
this.titlebar=null;
Figure.call(this);
this.setDeleteable(false);
this.setCanSnapToHelper(false);
this.setZOrder(Window.ZOrderIndex);
};
Window.prototype=new Figure;
Window.prototype.type="Window";
Window.ZOrderIndex=50000;
Window.setZOrderBaseIndex=function(index){
Window.ZOrderBaseIndex=index;
};
Window.prototype.hasFixedPosition=function(){
return true;
};
Window.prototype.hasTitleBar=function(){
return true;
};
Window.prototype.createHTMLElement=function(){
var item=Figure.prototype.createHTMLElement.call(this);
item.style.margin="0px";
item.style.padding="0px";
item.style.border="1px solid black";
item.style.backgroundImage="url(/skins/ext/images/gray/shapes/window_bg.png)";
//item.style.zIndex=Window.ZOrderBaseIndex;
item.style.cursor=null;
if(this.hasTitleBar()){
this.titlebar=document.createElement("div");
this.titlebar.style.position="absolute";
this.titlebar.style.left="0px";
this.titlebar.style.top="0px";
this.titlebar.style.width=this.getWidth()+"px";
this.titlebar.style.height="15px";
this.titlebar.style.margin="0px";
this.titlebar.style.padding="0px";
this.titlebar.style.font="normal 10px verdana";
this.titlebar.style.backgroundColor="blue";
this.titlebar.style.borderBottom="2px solid gray";
this.titlebar.style.whiteSpace="nowrap";
this.titlebar.style.textAlign="center";
this.titlebar.style.backgroundImage="url(/skins/ext/images/gray/shapes/window_toolbar.png)";
this.textNode=document.createTextNode(this.title);
this.titlebar.appendChild(this.textNode);
item.appendChild(this.titlebar);
}
return item;
};
Window.prototype.setDocumentDirty=function(_3b99){
};
Window.prototype.onDragend=function(){
};
Window.prototype.onDragstart=function(x,y){
if(this.titlebar==null){
return false;
}
if(this.canDrag==true&&x<parseInt(this.titlebar.style.width)&&y<parseInt(this.titlebar.style.height)){
return true;
}
return false;
};
Window.prototype.isSelectable=function(){
return false;
};
Window.prototype.setCanDrag=function(flag){
Figure.prototype.setCanDrag.call(this,flag);
this.html.style.cursor="";
if(this.titlebar==null){
return;
}
if(flag){
this.titlebar.style.cursor="move";
}else{
this.titlebar.style.cursor="";
}
};
Window.prototype.setWorkflow=function(_3b9d){
var _3b9e=this.workflow;
Figure.prototype.setWorkflow.call(this,_3b9d);
if(_3b9e!=null){
_3b9e.removeSelectionListener(this);
}
if(this.workflow!=null){
this.workflow.addSelectionListener(this);
}
};
Window.prototype.setDimension=function(w,h){
Figure.prototype.setDimension.call(this,w,h);
if(this.titlebar!=null){
this.titlebar.style.width=this.getWidth()+"px";
}
};
Window.prototype.setTitle=function(title){
this.title=title;
};
Window.prototype.getMinWidth=function(){
return 50;
};
Window.prototype.getMinHeight=function(){
return 50;
};
Window.prototype.isResizeable=function(){
return false;
};
Window.prototype.setAlpha=function(_3ba2){
};
Window.prototype.setBackgroundColor=function(color){
this.bgColor=color;
if(this.bgColor!=null){
this.html.style.backgroundColor=this.bgColor.getHTMLStyle();
}else{
this.html.style.backgroundColor="transparent";
this.html.style.backgroundImage="";
}
};
Window.prototype.setColor=function(color){
this.lineColor=color;
if(this.lineColor!=null){
this.html.style.border=this.lineStroke+"px solid "+this.lineColor.getHTMLStyle();
}else{
this.html.style.border="0px";
}
};
Window.prototype.setLineWidth=function(w){
this.lineStroke=w;
this.html.style.border=this.lineStroke+"px solid black";
};
Window.prototype.onSelectionChanged=function(_3ba6){
};
Button=function(_40ad,width,_40af){
this.x=0;
this.y=0;
this.id=this.generateUId();
this.enabled=true;
this.active=false;
this.palette=_40ad;
if(width&&_40af){
this.setDimension(width,_40af);
}else{
this.setDimension(24,24);
}
this.html=this.createHTMLElement();
};
Button.prototype.type="Button";
Button.prototype.dispose=function(){
};
Button.prototype.getImageUrl=function(){
if(this.enabled){
return this.type+".png";
}else{
return this.type+"_disabled.png";
}
};
Button.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height=this.width+"px";
item.style.width=this.height+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.outline="none";
if(this.getImageUrl()!=null){
item.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
item.style.backgroundImage="";
}
var oThis=this;
this.omousedown=function(event){
if(oThis.enabled){
oThis.setActive(true);
}
event.cancelBubble=true;
event.returnValue=false;
};
this.omouseup=function(event){
if(oThis.enabled){
oThis.setActive(false);
oThis.execute();
}
event.cancelBubble=true;
event.returnValue=false;
};
if(item.addEventListener){
item.addEventListener("mousedown",this.omousedown,false);
item.addEventListener("mouseup",this.omouseup,false);
}else{
if(item.attachEvent){
item.attachEvent("onmousedown",this.omousedown);
item.attachEvent("onmouseup",this.omouseup);
}
}
return item;
};
Button.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
Button.prototype.execute=function(){
};
Button.prototype.setTooltip=function(_40b4){
this.tooltip=_40b4;
if(this.tooltip!=null){
this.html.title=this.tooltip;
}else{
this.html.title="";
}
};
Button.prototype.setActive=function(flag){
if(!this.enabled){
return;
}
this.active=flag;
if(flag==true){
this.html.style.border="2px inset";
}else{
this.html.style.border="0px";
}
};
Button.prototype.isActive=function(){
return this.active;
};
Button.prototype.setEnabled=function(flag){
this.enabled=flag;
if(this.getImageUrl()!=null){
this.html.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
this.html.style.backgroundImage="";
}
};
Button.prototype.setDimension=function(w,h){
this.width=w;
this.height=h;
if(this.html==null){
return;
}
this.html.style.width=this.width+"px";
this.html.style.height=this.height+"px";
};
Button.prototype.setPosition=function(xPos,yPos){
this.x=Math.max(0,xPos);
this.y=Math.max(0,yPos);
if(this.html==null){
return;
}
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
};
Button.prototype.getWidth=function(){
return this.width;
};
Button.prototype.getHeight=function(){
return this.height;
};
Button.prototype.getY=function(){
return this.y;
};
Button.prototype.getX=function(){
return this.x;
};
Button.prototype.getPosition=function(){
return new Point(this.x,this.y);
};
Button.prototype.getToolPalette=function(){
return this.palette;
};
Button.prototype.generateUId=function(){
var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var _40bc=10;
var _40bd=10;
nbTry=0;
while(nbTry<1000){
var id="";
for(var i=0;i<_40bc;i++){
var rnum=Math.floor(Math.random()*chars.length);
id+=chars.substring(rnum,rnum+1);
}
elem=document.getElementById(id);
if(!elem){
return id;
}
nbTry+=1;
}
return null;
};
ToggleButton=function(_3e78){
Button.call(this,_3e78);
this.isDownFlag=false;
};
ToggleButton.prototype=new Button;
ToggleButton.prototype.type="ToggleButton";
ToggleButton.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height="24px";
item.style.width="24px";
item.style.margin="0px";
item.style.padding="0px";
if(this.getImageUrl()!=null){
item.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
item.style.backgroundImage="";
}
var oThis=this;
this.omousedown=function(event){
if(oThis.enabled){
if(!oThis.isDown()){
Button.prototype.setActive.call(oThis,true);
}
}
event.cancelBubble=true;
event.returnValue=false;
};
this.omouseup=function(event){
if(oThis.enabled){
if(oThis.isDown()){
Button.prototype.setActive.call(oThis,false);
}
oThis.isDownFlag=!oThis.isDownFlag;
oThis.execute();
}
event.cancelBubble=true;
event.returnValue=false;
};
if(item.addEventListener){
item.addEventListener("mousedown",this.omousedown,false);
item.addEventListener("mouseup",this.omouseup,false);
}else{
if(item.attachEvent){
item.attachEvent("onmousedown",this.omousedown);
item.attachEvent("onmouseup",this.omouseup);
}
}
return item;
};
ToggleButton.prototype.isDown=function(){
return this.isDownFlag;
};
ToggleButton.prototype.setActive=function(flag){
Button.prototype.setActive.call(this,flag);
this.isDownFlag=flag;
};
ToggleButton.prototype.execute=function(){
};
ToolGeneric=function(_39ec){
this.x=0;
this.y=0;
this.enabled=true;
this.tooltip=null;
this.palette=_39ec;
this.setDimension(10,10);
this.html=this.createHTMLElement();
};
ToolGeneric.prototype.type="ToolGeneric";
ToolGeneric.prototype.dispose=function(){
};
ToolGeneric.prototype.getImageUrl=function(){
if(this.enabled){
return this.type+".png";
}else{
return this.type+"_disabled.png";
}
};
ToolGeneric.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.id=this.id;
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.height="24px";
item.style.width="24px";
item.style.margin="0px";
item.style.padding="0px";
if(this.getImageUrl()!=null){
item.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
item.style.backgroundImage="";
}
var oThis=this;
this.click=function(event){
if(oThis.enabled){
oThis.palette.setActiveTool(oThis);
}
event.cancelBubble=true;
event.returnValue=false;
};
if(item.addEventListener){
item.addEventListener("click",this.click,false);
}else{
if(item.attachEvent){
item.attachEvent("onclick",this.click);
}
}
return item;
};
ToolGeneric.prototype.getHTMLElement=function(){
if(this.html==null){
this.html=this.createHTMLElement();
}
return this.html;
};
ToolGeneric.prototype.execute=function(x,y){
if(this.enabled){
this.palette.setActiveTool(null);
}
};
ToolGeneric.prototype.setTooltip=function(_39f2){
this.tooltip=_39f2;
if(this.tooltip!=null){
this.html.title=this.tooltip;
}else{
this.html.title="";
}
};
ToolGeneric.prototype.setActive=function(flag){
if(!this.enabled){
return;
}
if(flag==true){
this.html.style.border="2px inset";
}else{
this.html.style.border="0px";
}
};
ToolGeneric.prototype.setEnabled=function(flag){
this.enabled=flag;
if(this.getImageUrl()!=null){
this.html.style.backgroundImage="url("+this.getImageUrl()+")";
}else{
this.html.style.backgroundImage="";
}
};
ToolGeneric.prototype.setDimension=function(w,h){
this.width=w;
this.height=h;
if(this.html==null){
return;
}
this.html.style.width=this.width+"px";
this.html.style.height=this.height+"px";
};
ToolGeneric.prototype.setPosition=function(xPos,yPos){
this.x=Math.max(0,xPos);
this.y=Math.max(0,yPos);
if(this.html==null){
return;
}
this.html.style.left=this.x+"px";
this.html.style.top=this.y+"px";
};
ToolGeneric.prototype.getWidth=function(){
return this.width;
};
ToolGeneric.prototype.getHeight=function(){
return this.height;
};
ToolGeneric.prototype.getY=function(){
return this.y;
};
ToolGeneric.prototype.getX=function(){
return this.x;
};
ToolGeneric.prototype.getPosition=function(){
return new Point(this.x,this.y);
};
ToolPalette=function(title){
Window.call(this,title);
this.setDimension(75,400);
this.activeTool=null;
this.children=new Object();
};
ToolPalette.prototype=new Window;
ToolPalette.prototype.type="ToolPalette";
ToolPalette.prototype.dispose=function(){
Window.prototype.dispose.call(this);
};
ToolPalette.prototype.createHTMLElement=function(){
var item=Window.prototype.createHTMLElement.call(this);
this.scrollarea=document.createElement("div");
this.scrollarea.style.position="absolute";
this.scrollarea.style.left="0px";
if(this.hasTitleBar()){
this.scrollarea.style.top="15px";
}else{
this.scrollarea.style.top="0px";
}
this.scrollarea.style.width=this.getWidth()+"px";
this.scrollarea.style.height="15px";
this.scrollarea.style.margin="0px";
this.scrollarea.style.padding="0px";
this.scrollarea.style.font="normal 10px verdana";
this.scrollarea.style.borderBottom="2px solid gray";
this.scrollarea.style.whiteSpace="nowrap";
this.scrollarea.style.textAlign="center";
this.scrollarea.style.overflowX="auto";
this.scrollarea.style.overflowY="auto";
this.scrollarea.style.overflow="auto";
item.appendChild(this.scrollarea);
return item;
};
ToolPalette.prototype.setDimension=function(w,h){
Window.prototype.setDimension.call(this,w,h);
if(this.scrollarea!=null){
this.scrollarea.style.width=this.getWidth()+"px";
if(this.hasTitleBar()){
this.scrollarea.style.height=(this.getHeight()-15)+"px";
}else{
this.scrollarea.style.height=this.getHeight()+"px";
}
}
};
ToolPalette.prototype.addChild=function(item){
this.children[item.id]=item;
this.scrollarea.appendChild(item.getHTMLElement());
};
ToolPalette.prototype.getChild=function(id){
return this.children[id];
};
ToolPalette.prototype.getActiveTool=function(){
return this.activeTool;
};
ToolPalette.prototype.setActiveTool=function(tool){
if(this.activeTool!=tool&&this.activeTool!=null){
this.activeTool.setActive(false);
}
if(tool!=null){
tool.setActive(true);
}
this.activeTool=tool;
};
Dialog=function(title){
this.buttonbar=null;
if(title){
Window.call(this,title);
}else{
Window.call(this,"Dialog");
}
this.setDimension(400,300);
};
Dialog.prototype=new Window;
Dialog.prototype.type="Dialog";
Dialog.prototype.createHTMLElement=function(){
var item=Window.prototype.createHTMLElement.call(this);
var oThis=this;
this.buttonbar=document.createElement("div");
this.buttonbar.style.position="absolute";
this.buttonbar.style.left="0px";
this.buttonbar.style.bottom="0px";
this.buttonbar.style.width=this.getWidth()+"px";
this.buttonbar.style.height="30px";
this.buttonbar.style.margin="0px";
this.buttonbar.style.padding="0px";
this.buttonbar.style.font="normal 10px verdana";
this.buttonbar.style.backgroundColor="#C0C0C0";
this.buttonbar.style.borderBottom="2px solid gray";
this.buttonbar.style.whiteSpace="nowrap";
this.buttonbar.style.textAlign="center";
this.okbutton=document.createElement("button");
this.okbutton.style.border="1px solid gray";
this.okbutton.style.font="normal 10px verdana";
this.okbutton.style.width="80px";
this.okbutton.style.margin="5px";
this.okbutton.innerHTML="Ok";
this.okbutton.onclick=function(){
oThis.onOk();
};
this.buttonbar.appendChild(this.okbutton);
this.cancelbutton=document.createElement("button");
this.cancelbutton.innerHTML="Cancel";
this.cancelbutton.style.font="normal 10px verdana";
this.cancelbutton.style.border="1px solid gray";
this.cancelbutton.style.width="80px";
this.cancelbutton.style.margin="5px";
this.cancelbutton.onclick=function(){
oThis.onCancel();
};
this.buttonbar.appendChild(this.cancelbutton);
item.appendChild(this.buttonbar);
return item;
};
Dialog.prototype.onOk=function(){
this.workflow.removeFigure(this);
};
Dialog.prototype.onCancel=function(){
this.workflow.removeFigure(this);
};
Dialog.prototype.setDimension=function(w,h){
Window.prototype.setDimension.call(this,w,h);
if(this.buttonbar!=null){
this.buttonbar.style.width=this.getWidth()+"px";
}
};
Dialog.prototype.setWorkflow=function(_31c1){
Window.prototype.setWorkflow.call(this,_31c1);
this.setFocus();
};
Dialog.prototype.setFocus=function(){
};
Dialog.prototype.onSetDocumentDirty=function(){
};
InputDialog=function(){
Dialog.call(this);
this.setDimension(400,100);
};
InputDialog.prototype=new Dialog;
InputDialog.prototype.type="InputDialog";
InputDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
return item;
};
InputDialog.prototype.onOk=function(){
this.workflow.removeFigure(this);
};
InputDialog.prototype.onCancel=function(){
this.workflow.removeFigure(this);
};
PropertyDialog=function(_3f50,_3f51,label){
this.figure=_3f50;
this.propertyName=_3f51;
this.label=label;
Dialog.call(this);
this.setDimension(400,120);
};
PropertyDialog.prototype=new Dialog;
PropertyDialog.prototype.type="PropertyDialog";
PropertyDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
var _3f54=document.createElement("form");
_3f54.style.position="absolute";
_3f54.style.left="10px";
_3f54.style.top="30px";
_3f54.style.width="375px";
_3f54.style.font="normal 10px verdana";
item.appendChild(_3f54);
this.labelDiv=document.createElement("div");
this.labelDiv.innerHTML=this.label;
this.disableTextSelection(this.labelDiv);
_3f54.appendChild(this.labelDiv);
this.input=document.createElement("input");
this.input.style.border="1px solid gray";
this.input.style.font="normal 10px verdana";
this.input.type="text";
var value=this.figure.getProperty(this.propertyName);
if(value){
this.input.value=value;
}else{
this.input.value="";
}
this.input.style.width="100%";
_3f54.appendChild(this.input);
this.input.focus();
return item;
};
PropertyDialog.prototype.onOk=function(){
Dialog.prototype.onOk.call(this);
this.figure.setProperty(this.propertyName,this.input.value);
};
AnnotationDialog=function(_2e5e){
this.figure=_2e5e;
Dialog.call(this);
this.setDimension(400,100);
};
AnnotationDialog.prototype=new Dialog;
AnnotationDialog.prototype.type="AnnotationDialog";
AnnotationDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
var _2e60=document.createElement("form");
_2e60.style.position="absolute";
_2e60.style.left="10px";
_2e60.style.top="30px";
_2e60.style.width="375px";
_2e60.style.font="normal 10px verdana";
item.appendChild(_2e60);
this.label=document.createTextNode("Text");
_2e60.appendChild(this.label);
this.input=document.createElement("input");
this.input.style.border="1px solid gray";
this.input.style.font="normal 10px verdana";
this.input.type="text";
var value=this.figure.getText();
if(value){
this.input.value=value;
}else{
this.input.value="";
}
this.input.style.width="100%";
_2e60.appendChild(this.input);
this.input.focus();
return item;
};
AnnotationDialog.prototype.onOk=function(){
this.workflow.getCommandStack().execute(new CommandSetText(this.figure,this.input.value));
this.workflow.removeFigure(this);
};
PropertyWindow=function(){
this.currentSelection=null;
Window.call(this,"Property Window");
this.setDimension(200,100);
};
PropertyWindow.prototype=new Window;
PropertyWindow.prototype.type="PropertyWindow";
PropertyWindow.prototype.dispose=function(){
Window.prototype.dispose.call(this);
};
PropertyWindow.prototype.createHTMLElement=function(){
var item=Window.prototype.createHTMLElement.call(this);
item.appendChild(this.createLabel("Type:",15,25));
item.appendChild(this.createLabel("X :",15,50));
item.appendChild(this.createLabel("Y :",15,70));
item.appendChild(this.createLabel("Width :",85,50));
item.appendChild(this.createLabel("Height :",85,70));
this.labelType=this.createLabel("",50,25);
this.labelX=this.createLabel("",40,50);
this.labelY=this.createLabel("",40,70);
this.labelWidth=this.createLabel("",135,50);
this.labelHeight=this.createLabel("",135,70);
this.labelType.style.fontWeight="normal";
this.labelX.style.fontWeight="normal";
this.labelY.style.fontWeight="normal";
this.labelWidth.style.fontWeight="normal";
this.labelHeight.style.fontWeight="normal";
item.appendChild(this.labelType);
item.appendChild(this.labelX);
item.appendChild(this.labelY);
item.appendChild(this.labelWidth);
item.appendChild(this.labelHeight);
return item;
};
PropertyWindow.prototype.onSelectionChanged=function(_31cf){
Window.prototype.onSelectionChanged.call(this,_31cf);
if(this.currentSelection!=null){
this.currentSelection.detachMoveListener(this);
}
this.currentSelection=_31cf;
if(_31cf!=null&&_31cf!=this){
this.labelType.innerHTML=_31cf.type;
if(_31cf.getX){
this.labelX.innerHTML=_31cf.getX();
this.labelY.innerHTML=_31cf.getY();
this.labelWidth.innerHTML=_31cf.getWidth();
this.labelHeight.innerHTML=_31cf.getHeight();
this.currentSelection=_31cf;
this.currentSelection.attachMoveListener(this);
}else{
this.labelX.innerHTML="";
this.labelY.innerHTML="";
this.labelWidth.innerHTML="";
this.labelHeight.innerHTML="";
}
}else{
this.labelType.innerHTML="<none>";
this.labelX.innerHTML="";
this.labelY.innerHTML="";
this.labelWidth.innerHTML="";
this.labelHeight.innerHTML="";
}
};
PropertyWindow.prototype.getCurrentSelection=function(){
return this.currentSelection;
};
PropertyWindow.prototype.onOtherFigureMoved=function(_31d0){
if(_31d0==this.currentSelection){
this.onSelectionChanged(_31d0);
}
};
PropertyWindow.prototype.createLabel=function(text,x,y){
var l=document.createElement("div");
l.style.position="absolute";
l.style.left=x+"px";
l.style.top=y+"px";
l.style.font="normal 10px verdana";
l.style.whiteSpace="nowrap";
l.style.fontWeight="bold";
l.innerHTML=text;
return l;
};
ColorDialog=function(){
this.maxValue={"h":"359","s":"100","v":"100"};
this.HSV={0:359,1:100,2:100};
this.slideHSV={0:359,1:100,2:100};
this.SVHeight=165;
this.wSV=162;
this.wH=162;
Dialog.call(this,"Color Chooser");
this.loadSV();
this.setColor(new Color(255,0,0));
this.setDimension(219,244);
};
ColorDialog.prototype=new Dialog;
ColorDialog.prototype.type="ColorDialog";
ColorDialog.prototype.createHTMLElement=function(){
var oThis=this;
var item=Dialog.prototype.createHTMLElement.call(this);
this.outerDiv=document.createElement("div");
this.outerDiv.id="plugin";
this.outerDiv.style.top="15px";
this.outerDiv.style.left="0px";
this.outerDiv.style.width="201px";
this.outerDiv.style.position="absolute";
this.outerDiv.style.padding="9px";
this.outerDiv.display="block";
this.outerDiv.style.background="#0d0d0d";
this.plugHEX=document.createElement("div");
this.plugHEX.id="plugHEX";
this.plugHEX.innerHTML="F1FFCC";
this.plugHEX.style.color="white";
this.plugHEX.style.font="normal 10px verdana";
this.outerDiv.appendChild(this.plugHEX);
this.SV=document.createElement("div");
this.SV.onmousedown=function(event){
oThis.mouseDownSV(oThis.SVslide,event);
};
this.SV.id="SV";
this.SV.style.cursor="crosshair";
this.SV.style.background="#FF0000 url(SatVal.png)";
this.SV.style.position="absolute";
this.SV.style.height="166px";
this.SV.style.width="167px";
this.SV.style.marginRight="10px";
this.SV.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='SatVal.png', sizingMethod='scale')";
this.SV.style["float"]="left";
this.outerDiv.appendChild(this.SV);
this.SVslide=document.createElement("div");
this.SVslide.onmousedown=function(event){
oThis.mouseDownSV(event);
};
this.SVslide.style.top="40px";
this.SVslide.style.left="40px";
this.SVslide.style.position="absolute";
this.SVslide.style.cursor="crosshair";
this.SVslide.style.background="url(slide.gif)";
this.SVslide.style.height="9px";
this.SVslide.style.width="9px";
this.SVslide.style.lineHeight="1px";
this.outerDiv.appendChild(this.SVslide);
this.H=document.createElement("form");
this.H.id="H";
this.H.onmousedown=function(event){
oThis.mouseDownH(event);
};
this.H.style.border="1px solid #000000";
this.H.style.cursor="crosshair";
this.H.style.position="absolute";
this.H.style.width="19px";
this.H.style.top="28px";
this.H.style.left="191px";
this.outerDiv.appendChild(this.H);
this.Hslide=document.createElement("div");
this.Hslide.style.top="-7px";
this.Hslide.style.left="-8px";
this.Hslide.style.background="url(slideHue.gif)";
this.Hslide.style.height="5px";
this.Hslide.style.width="33px";
this.Hslide.style.position="absolute";
this.Hslide.style.lineHeight="1px";
this.H.appendChild(this.Hslide);
this.Hmodel=document.createElement("div");
this.Hmodel.style.height="1px";
this.Hmodel.style.width="19px";
this.Hmodel.style.lineHeight="1px";
this.Hmodel.style.margin="0px";
this.Hmodel.style.padding="0px";
this.Hmodel.style.fontSize="1px";
this.H.appendChild(this.Hmodel);
item.appendChild(this.outerDiv);
return item;
};
ColorDialog.prototype.onOk=function(){
Dialog.prototype.onOk.call(this);
};
browser=function(v){
return (Math.max(navigator.userAgent.toLowerCase().indexOf(v),0));
};
ColorDialog.prototype.showColor=function(c){
this.plugHEX.style.background="#"+c;
this.plugHEX.innerHTML=c;
};
ColorDialog.prototype.getSelectedColor=function(){
var rgb=this.hex2rgb(this.plugHEX.innerHTML);
return new Color(rgb[0],rgb[1],rgb[2]);
};
ColorDialog.prototype.setColor=function(color){
if(color==null){
color=new Color(100,100,100);
}
var hex=this.rgb2hex(Array(color.getRed(),color.getGreen(),color.getBlue()));
this.updateH(hex);
};
ColorDialog.prototype.XY=function(e,v){
var z=browser("msie")?Array(event.clientX+document.body.scrollLeft,event.clientY+document.body.scrollTop):Array(e.pageX,e.pageY);
return z[v];
};
ColorDialog.prototype.mkHSV=function(a,b,c){
return (Math.min(a,Math.max(0,Math.ceil((parseInt(c)/b)*a))));
};
ColorDialog.prototype.ckHSV=function(a,b){
if(a>=0&&a<=b){
return (a);
}else{
if(a>b){
return (b);
}else{
if(a<0){
return ("-"+oo);
}
}
}
};
ColorDialog.prototype.mouseDownH=function(e){
this.slideHSV[0]=this.HSV[0];
var oThis=this;
this.H.onmousemove=function(e){
oThis.dragH(e);
};
this.H.onmouseup=function(e){
oThis.H.onmousemove="";
oThis.H.onmouseup="";
};
this.dragH(e);
};
ColorDialog.prototype.dragH=function(e){
var y=this.XY(e,1)-this.getY()-40;
this.Hslide.style.top=(this.ckHSV(y,this.wH)-5)+"px";
this.slideHSV[0]=this.mkHSV(359,this.wH,this.Hslide.style.top);
this.updateSV();
this.showColor(this.commit());
this.SV.style.backgroundColor="#"+this.hsv2hex(Array(this.HSV[0],100,100));
};
ColorDialog.prototype.mouseDownSV=function(o,e){
this.slideHSV[0]=this.HSV[0];
var oThis=this;
function reset(){
oThis.SV.onmousemove="";
oThis.SV.onmouseup="";
oThis.SVslide.onmousemove="";
oThis.SVslide.onmouseup="";
}
this.SV.onmousemove=function(e){
oThis.dragSV(e);
};
this.SV.onmouseup=reset;
this.SVslide.onmousemove=function(e){
oThis.dragSV(e);
};
this.SVslide.onmouseup=reset;
this.dragSV(e);
};
ColorDialog.prototype.dragSV=function(e){
var x=this.XY(e,0)-this.getX()-1;
var y=this.XY(e,1)-this.getY()-20;
this.SVslide.style.left=this.ckHSV(x,this.wSV)+"px";
this.SVslide.style.top=this.ckHSV(y,this.wSV)+"px";
this.slideHSV[1]=this.mkHSV(100,this.wSV,this.SVslide.style.left);
this.slideHSV[2]=100-this.mkHSV(100,this.wSV,this.SVslide.style.top);
this.updateSV();
};
ColorDialog.prototype.commit=function(){
var r="hsv";
var z={};
var j="";
for(var i=0;i<=r.length-1;i++){
j=r.substr(i,1);
z[i]=(j=="h")?this.maxValue[j]-this.mkHSV(this.maxValue[j],this.wH,this.Hslide.style.top):this.HSV[i];
}
return (this.updateSV(this.hsv2hex(z)));
};
ColorDialog.prototype.updateSV=function(v){
this.HSV=v?this.hex2hsv(v):Array(this.slideHSV[0],this.slideHSV[1],this.slideHSV[2]);
if(!v){
v=this.hsv2hex(Array(this.slideHSV[0],this.slideHSV[1],this.slideHSV[2]));
}
this.showColor(v);
return v;
};
ColorDialog.prototype.loadSV=function(){
var z="";
for(var i=this.SVHeight;i>=0;i--){
z+="<div style=\"background:#"+this.hsv2hex(Array(Math.round((359/this.SVHeight)*i),100,100))+";\"><br/></div>";
}
this.Hmodel.innerHTML=z;
};
ColorDialog.prototype.updateH=function(v){
this.plugHEX.innerHTML=v;
this.HSV=this.hex2hsv(v);
this.SV.style.backgroundColor="#"+this.hsv2hex(Array(this.HSV[0],100,100));
this.SVslide.style.top=(parseInt(this.wSV-this.wSV*(this.HSV[1]/100))+20)+"px";
this.SVslide.style.left=(parseInt(this.wSV*(this.HSV[1]/100))+5)+"px";
this.Hslide.style.top=(parseInt(this.wH*((this.maxValue["h"]-this.HSV[0])/this.maxValue["h"]))-7)+"px";
};
ColorDialog.prototype.toHex=function(v){
v=Math.round(Math.min(Math.max(0,v),255));
return ("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16));
};
ColorDialog.prototype.hex2rgb=function(r){
return ({0:parseInt(r.substr(0,2),16),1:parseInt(r.substr(2,2),16),2:parseInt(r.substr(4,2),16)});
};
ColorDialog.prototype.rgb2hex=function(r){
return (this.toHex(r[0])+this.toHex(r[1])+this.toHex(r[2]));
};
ColorDialog.prototype.hsv2hex=function(h){
return (this.rgb2hex(this.hsv2rgb(h)));
};
ColorDialog.prototype.hex2hsv=function(v){
return (this.rgb2hsv(this.hex2rgb(v)));
};
ColorDialog.prototype.rgb2hsv=function(r){
var max=Math.max(r[0],r[1],r[2]);
var delta=max-Math.min(r[0],r[1],r[2]);
var H;
var S;
var V;
if(max!=0){
S=Math.round(delta/max*100);
if(r[0]==max){
H=(r[1]-r[2])/delta;
}else{
if(r[1]==max){
H=2+(r[2]-r[0])/delta;
}else{
if(r[2]==max){
H=4+(r[0]-r[1])/delta;
}
}
}
var H=Math.min(Math.round(H*60),360);
if(H<0){
H+=360;
}
}
return ({0:H?H:0,1:S?S:0,2:Math.round((max/255)*100)});
};
ColorDialog.prototype.hsv2rgb=function(r){
var R;
var B;
var G;
var S=r[1]/100;
var V=r[2]/100;
var H=r[0]/360;
if(S>0){
if(H>=1){
H=0;
}
H=6*H;
F=H-Math.floor(H);
A=Math.round(255*V*(1-S));
B=Math.round(255*V*(1-(S*F)));
C=Math.round(255*V*(1-(S*(1-F))));
V=Math.round(255*V);
switch(Math.floor(H)){
case 0:
R=V;
G=C;
B=A;
break;
case 1:
R=B;
G=V;
B=A;
break;
case 2:
R=A;
G=V;
B=C;
break;
case 3:
R=A;
G=B;
B=V;
break;
case 4:
R=C;
G=A;
B=V;
break;
case 5:
R=V;
G=A;
B=B;
break;
}
return ({0:R?R:0,1:G?G:0,2:B?B:0});
}else{
return ({0:(V=Math.round(V*255)),1:V,2:V});
}
};
LineColorDialog=function(_2e57){
ColorDialog.call(this);
this.figure=_2e57;
var color=_2e57.getColor();
this.updateH(this.rgb2hex(color.getRed(),color.getGreen(),color.getBlue()));
};
LineColorDialog.prototype=new ColorDialog;
LineColorDialog.prototype.type="LineColorDialog";
LineColorDialog.prototype.onOk=function(){
var _2e59=this.workflow;
ColorDialog.prototype.onOk.call(this);
if(typeof this.figure.setColor=="function"){
_2e59.getCommandStack().execute(new CommandSetColor(this.figure,this.getSelectedColor()));
if(_2e59.getCurrentSelection()==this.figure){
_2e59.setCurrentSelection(this.figure);
}
}
};
BackgroundColorDialog=function(_40a6){
ColorDialog.call(this);
this.figure=_40a6;
var color=_40a6.getBackgroundColor();
if(color!=null){
this.updateH(this.rgb2hex(color.getRed(),color.getGreen(),color.getBlue()));
}
};
BackgroundColorDialog.prototype=new ColorDialog;
BackgroundColorDialog.prototype.type="BackgroundColorDialog";
BackgroundColorDialog.prototype.onOk=function(){
var _40a8=this.workflow;
ColorDialog.prototype.onOk.call(this);
if(typeof this.figure.setBackgroundColor=="function"){
_40a8.getCommandStack().execute(new CommandSetBackgroundColor(this.figure,this.getSelectedColor()));
if(_40a8.getCurrentSelection()==this.figure){
_40a8.setCurrentSelection(this.figure);
}
}
};
AnnotationDialog=function(_2e5e){
this.figure=_2e5e;
Dialog.call(this);
this.setDimension(400,100);
};
AnnotationDialog.prototype=new Dialog;
AnnotationDialog.prototype.type="AnnotationDialog";
AnnotationDialog.prototype.createHTMLElement=function(){
var item=Dialog.prototype.createHTMLElement.call(this);
var _2e60=document.createElement("form");
_2e60.style.position="absolute";
_2e60.style.left="10px";
_2e60.style.top="30px";
_2e60.style.width="375px";
_2e60.style.font="normal 10px verdana";
item.appendChild(_2e60);
this.label=document.createTextNode("Text");
_2e60.appendChild(this.label);
this.input=document.createElement("input");
this.input.style.border="1px solid gray";
this.input.style.font="normal 10px verdana";
this.input.type="text";
var value=this.figure.getText();
if(value){
this.input.value=value;
}else{
this.input.value="";
}
this.input.style.width="100%";
_2e60.appendChild(this.input);
this.input.focus();
return item;
};
AnnotationDialog.prototype.onOk=function(){
this.workflow.getCommandStack().execute(new CommandSetText(this.figure,this.input.value));
this.workflow.removeFigure(this);
};
Command=function(label){
this.label=label;
};
Command.prototype.type="Command";
Command.prototype.getLabel=function(){
};
Command.prototype.canExecute=function(){
return true;
};
Command.prototype.execute=function(){
};
Command.prototype.undo=function(){
};
Command.prototype.redo=function(){
};
CommandStack=function(){
this.undostack=new Array();
this.redostack=new Array();
this.maxundo=50;
this.eventListeners=new ArrayList();
};
CommandStack.PRE_EXECUTE=1;
CommandStack.PRE_REDO=2;
CommandStack.PRE_UNDO=4;
CommandStack.POST_EXECUTE=8;
CommandStack.POST_REDO=16;
CommandStack.POST_UNDO=32;
CommandStack.POST_MASK=CommandStack.POST_EXECUTE|CommandStack.POST_UNDO|CommandStack.POST_REDO;
CommandStack.PRE_MASK=CommandStack.PRE_EXECUTE|CommandStack.PRE_UNDO|CommandStack.PRE_REDO;
CommandStack.prototype.type="CommandStack";
CommandStack.prototype.setUndoLimit=function(count){
this.maxundo=count;
};
CommandStack.prototype.markSaveLocation=function(){
this.undostack=new Array();
this.redostack=new Array();
};
CommandStack.prototype.execute=function(_3f6c){
if(_3f6c.canExecute()==false){
return;
}
this.notifyListeners(_3f6c,CommandStack.PRE_EXECUTE);
this.undostack.push(_3f6c);
_3f6c.execute();
this.redostack=new Array();
if(this.undostack.length>this.maxundo){
this.undostack=this.undostack.slice(this.undostack.length-this.maxundo);
}
this.notifyListeners(_3f6c,CommandStack.POST_EXECUTE);
};
CommandStack.prototype.undo=function(){
var _3f6d=this.undostack.pop();
if(_3f6d){
this.notifyListeners(_3f6d,CommandStack.PRE_UNDO);
this.redostack.push(_3f6d);
_3f6d.undo();
this.notifyListeners(_3f6d,CommandStack.POST_UNDO);
}
};
CommandStack.prototype.redo=function(){
var _3f6e=this.redostack.pop();
if(_3f6e){
this.notifyListeners(_3f6e,CommandStack.PRE_REDO);
this.undostack.push(_3f6e);
_3f6e.redo();
this.notifyListeners(_3f6e,CommandStack.POST_REDO);
}
};
CommandStack.prototype.canRedo=function(){
return this.redostack.length>0;
};
CommandStack.prototype.canUndo=function(){
return this.undostack.length>0;
};
CommandStack.prototype.addCommandStackEventListener=function(_3f6f){
this.eventListeners.add(_3f6f);
};
CommandStack.prototype.removeCommandStackEventListener=function(_3f70){
this.eventListeners.remove(_3f70);
};
CommandStack.prototype.notifyListeners=function(_3f71,state){
var event=new CommandStackEvent(_3f71,state);
var size=this.eventListeners.getSize();
for(var i=0;i<size;i++){
this.eventListeners.get(i).stackChanged(event);
}
};
CommandStackEvent=function(_3e48,_3e49){
this.command=_3e48;
this.details=_3e49;
};
CommandStackEvent.prototype.type="CommandStackEvent";
CommandStackEvent.prototype.getCommand=function(){
return this.command;
};
CommandStackEvent.prototype.getDetails=function(){
return this.details;
};
CommandStackEvent.prototype.isPostChangeEvent=function(){
return 0!=(this.getDetails()&CommandStack.POST_MASK);
};
CommandStackEvent.prototype.isPreChangeEvent=function(){
return 0!=(this.getDetails()&CommandStack.PRE_MASK);
};
CommandStackEventListener=function(){
};
CommandStackEventListener.prototype.type="CommandStackEventListener";
CommandStackEventListener.prototype.stackChanged=function(event){
};
CommandAdd=function(_4089,_408a,x,y,_408d){
Command.call(this,"add figure");
this.parent=_408d;
this.figure=_408a;
this.x=x;
this.y=y;
this.workflow=_4089;
};
CommandAdd.prototype=new Command;
CommandAdd.prototype.type="CommandAdd";
CommandAdd.prototype.execute=function(){
this.redo();
};
CommandAdd.prototype.redo=function(){
if(this.x&&this.y){
this.workflow.addFigure(this.figure,this.x,this.y);
}else{
this.workflow.addFigure(this.figure);
}
this.workflow.setCurrentSelection(this.figure);
if(this.parent!=null){
this.parent.addChild(this.figure);
}
};
CommandAdd.prototype.undo=function(){
this.workflow.removeFigure(this.figure);
this.workflow.setCurrentSelection(null);
if(this.parent!=null){
this.parent.removeChild(this.figure);
}
};
CommandDelete=function(_3f13){
Command.call(this,"delete figure");
this.parent=_3f13.parent;
this.figure=_3f13;
this.workflow=_3f13.workflow;
this.connections=null;
};
CommandDelete.prototype=new Command;
CommandDelete.prototype.type="CommandDelete";
CommandDelete.prototype.execute=function(){
this.redo();
};
CommandDelete.prototype.undo=function(){
this.workflow.addFigure(this.figure);
if(this.figure instanceof Connection){
this.figure.reconnect();
}
this.workflow.setCurrentSelection(this.figure);
if(this.parent!=null){
this.parent.addChild(this.figure);
}
for(var i=0;i<this.connections.getSize();++i){
this.workflow.addFigure(this.connections.get(i));
this.connections.get(i).reconnect();
}
};
CommandDelete.prototype.redo=function(){
this.workflow.removeFigure(this.figure);
this.workflow.setCurrentSelection(null);
if(this.figure.getPorts&&this.connections==null){
this.connections=new ArrayList();
var ports=this.figure.getPorts();
for(var i=0;i<ports.getSize();i++){
if(ports.get(i).getConnections){
this.connections.addAll(ports.get(i).getConnections());
}
}
}
if(this.connections==null){
this.connections=new ArrayList();
}
if(this.parent!=null){
this.parent.removeChild(this.figure);
}
for(var i=0;i<this.connections.getSize();++i){
this.workflow.removeFigure(this.connections.get(i));
}
};
CommandMove=function(_3f21,x,y){
Command.call(this,"move figure");
this.figure=_3f21;
this.oldX=x;
this.oldY=y;
this.oldCompartment=_3f21.getParent();
};
CommandMove.prototype=new Command;
CommandMove.prototype.type="CommandMove";
CommandMove.prototype.setPosition=function(x,y){
this.newX=x;
this.newY=y;
this.newCompartment=this.figure.workflow.getBestCompartmentFigure(x,y,this.figure);
};
CommandMove.prototype.canExecute=function(){
return this.newX!=this.oldX||this.newY!=this.oldY;
};
CommandMove.prototype.execute=function(){
this.redo();
};
CommandMove.prototype.undo=function(){
this.figure.setPosition(this.oldX,this.oldY);
if(this.newCompartment!=null){
this.newCompartment.removeChild(this.figure);
}
if(this.oldCompartment!=null){
this.oldCompartment.addChild(this.figure);
}
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandMove.prototype.redo=function(){
this.figure.setPosition(this.newX,this.newY);
if(this.oldCompartment!=null){
this.oldCompartment.removeChild(this.figure);
}
if(this.newCompartment!=null){
this.newCompartment.addChild(this.figure);
}
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandResize=function(_3e82,width,_3e84){
Command.call(this,"resize figure");
this.figure=_3e82;
this.oldWidth=width;
this.oldHeight=_3e84;
};
CommandResize.prototype=new Command;
CommandResize.prototype.type="CommandResize";
CommandResize.prototype.setDimension=function(width,_3e86){
this.newWidth=width;
this.newHeight=_3e86;
};
CommandResize.prototype.canExecute=function(){
return this.newWidth!=this.oldWidth||this.newHeight!=this.oldHeight;
};
CommandResize.prototype.execute=function(){
this.redo();
};
CommandResize.prototype.undo=function(){
this.figure.setDimension(this.oldWidth,this.oldHeight);
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandResize.prototype.redo=function(){
this.figure.setDimension(this.newWidth,this.newHeight);
this.figure.workflow.moveResizeHandles(this.figure);
};
CommandSetText=function(_41ee,text){
Command.call(this,"set text");
this.figure=_41ee;
this.newText=text;
this.oldText=_41ee.getText();
};
CommandSetText.prototype=new Command;
CommandSetText.prototype.type="CommandSetText";
CommandSetText.prototype.execute=function(){
this.redo();
};
CommandSetText.prototype.redo=function(){
this.figure.setText(this.newText);
};
CommandSetText.prototype.undo=function(){
this.figure.setText(this.oldText);
};
CommandSetColor=function(_3a42,color){
Command.call(this,"set color");
this.figure=_3a42;
this.newColor=color;
this.oldColor=_3a42.getColor();
};
CommandSetColor.prototype=new Command;
CommandSetColor.prototype.type="CommandSetColor";
CommandSetColor.prototype.execute=function(){
this.redo();
};
CommandSetColor.prototype.undo=function(){
this.figure.setColor(this.oldColor);
};
CommandSetColor.prototype.redo=function(){
this.figure.setColor(this.newColor);
};
CommandSetBackgroundColor=function(_2d19,color){
Command.call(this,"set background color");
this.figure=_2d19;
this.newColor=color;
this.oldColor=_2d19.getBackgroundColor();
};
CommandSetBackgroundColor.prototype=new Command;
CommandSetBackgroundColor.prototype.type="CommandSetBackgroundColor";
CommandSetBackgroundColor.prototype.execute=function(){
this.redo();
};
CommandSetBackgroundColor.prototype.undo=function(){
this.figure.setBackgroundColor(this.oldColor);
};
CommandSetBackgroundColor.prototype.redo=function(){
this.figure.setBackgroundColor(this.newColor);
};
CommandConnect=function(_4063,_4064,_4065){
Command.call(this,"create connection");
this.workflow=_4063;
this.source=_4064;
this.target=_4065;
this.connection=null;
};
CommandConnect.prototype=new Command;
CommandConnect.prototype.type="CommandConnect";
CommandConnect.prototype.setConnection=function(_4066){
this.connection=_4066;
};
CommandConnect.prototype.execute=function(){
if(this.connection==null){
this.connection=new Connection();
}
this.connection.setSource(this.source);
this.connection.setTarget(this.target);
this.workflow.addFigure(this.connection);
};
CommandConnect.prototype.redo=function(){
this.workflow.addFigure(this.connection);
this.connection.reconnect();
};
CommandConnect.prototype.undo=function(){
this.workflow.removeFigure(this.connection);
};
CommandReconnect=function(con){
Command.call(this,"reconnect connection");
this.con=con;
this.oldSourcePort=con.getSource();
this.oldTargetPort=con.getTarget();
this.oldRouter=con.getRouter();
};
CommandReconnect.prototype=new Command;
CommandReconnect.prototype.type="CommandReconnect";
CommandReconnect.prototype.canExecute=function(){
return true;
};
CommandReconnect.prototype.setNewPorts=function(_3548,_3549){
this.newSourcePort=_3548;
this.newTargetPort=_3549;
};
CommandReconnect.prototype.execute=function(){
this.redo();
};
CommandReconnect.prototype.undo=function(){
this.con.setSource(this.oldSourcePort);
this.con.setTarget(this.oldTargetPort);
this.con.setRouter(this.oldRouter);
if(this.con.getWorkflow().getCurrentSelection()==this.con){
this.con.getWorkflow().showLineResizeHandles(this.con);
}
};
CommandReconnect.prototype.redo=function(){
this.con.setSource(this.newSourcePort);
this.con.setTarget(this.newTargetPort);
this.con.setRouter(this.oldRouter);
if(this.con.getWorkflow().getCurrentSelection()==this.con){
this.con.getWorkflow().showLineResizeHandles(this.con);
}
};
CommandMoveLine=function(line,_359c,_359d,endX,endY){
Command.call(this,"move line");
this.line=line;
this.startX1=_359c;
this.startY1=_359d;
this.endX1=endX;
this.endY1=endY;
};
CommandMoveLine.prototype=new Command;
CommandMoveLine.prototype.type="CommandMoveLine";
CommandMoveLine.prototype.canExecute=function(){
return this.startX1!=this.startX2||this.startY1!=this.startY2||this.endX1!=this.endX2||this.endY1!=this.endY2;
};
CommandMoveLine.prototype.setEndPoints=function(_35a0,_35a1,endX,endY){
this.startX2=_35a0;
this.startY2=_35a1;
this.endX2=endX;
this.endY2=endY;
};
CommandMoveLine.prototype.execute=function(){
this.redo();
};
CommandMoveLine.prototype.undo=function(){
this.line.setStartPoint(this.startX1,this.startY1);
this.line.setEndPoint(this.endX1,this.endY1);
if(this.line.workflow.getCurrentSelection()==this.line){
this.line.workflow.showLineResizeHandles(this.line);
}
};
CommandMoveLine.prototype.redo=function(){
this.line.setStartPoint(this.startX2,this.startY2);
this.line.setEndPoint(this.endX2,this.endY2);
if(this.line.workflow.getCurrentSelection()==this.line){
this.line.workflow.showLineResizeHandles(this.line);
}
};
Menu=function(){
this.menuItems=new ArrayList();
Figure.call(this);
this.setSelectable(false);
this.setDeleteable(false);
this.setCanDrag(false);
this.setResizeable(false);
this.setSelectable(false);
this.setZOrder(10000);
this.dirty=false;
};
Menu.prototype=new Figure;
Menu.prototype.type="Menu";
Menu.prototype.createHTMLElement=function(){
var item=document.createElement("div");
item.style.position="absolute";
item.style.left=this.x+"px";
item.style.top=this.y+"px";
item.style.margin="0px";
item.style.padding="0px";
item.style.zIndex=""+Figure.ZOrderBaseIndex;
item.style.border="1px solid gray";
item.style.background="lavender";
item.style.cursor="pointer";
return item;
};
Menu.prototype.setWorkflow=function(_41f4){
this.workflow=_41f4;
};
Menu.prototype.appendMenuItem=function(item){
this.menuItems.add(item);
item.parentMenu=this;
this.dirty=true;
};
Menu.prototype.getHTMLElement=function(){
var html=Figure.prototype.getHTMLElement.call(this);
if(this.dirty){
this.createList();
}
return html;
};
Menu.prototype.createList=function(){
this.dirty=false;
this.html.innerHTML="";
var oThis=this;
for(var i=0;i<this.menuItems.getSize();i++){
var item=this.menuItems.get(i);
var li=document.createElement("a");
li.innerHTML=item.getLabel();
li.style.display="block";
li.style.fontFamily="Verdana, Arial, Helvetica, sans-serif";
li.style.fontSize="9pt";
li.style.color="dimgray";
li.style.borderBottom="1px solid silver";
li.style.paddingLeft="5px";
li.style.paddingRight="5px";
li.style.cursor="pointer";
this.html.appendChild(li);
li.menuItem=item;
if(li.addEventListener){
li.addEventListener("click",function(event){
var _41fc=arguments[0]||window.event;
_41fc.cancelBubble=true;
_41fc.returnValue=false;
var diffX=_41fc.clientX;
var diffY=_41fc.clientY;
var _41ff=document.body.parentNode.scrollLeft;
var _4200=document.body.parentNode.scrollTop;
this.menuItem.execute(diffX+_41ff,diffY+_4200);
},false);
li.addEventListener("mouseup",function(event){
event.cancelBubble=true;
event.returnValue=false;
},false);
li.addEventListener("mousedown",function(event){
event.cancelBubble=true;
event.returnValue=false;
},false);
li.addEventListener("mouseover",function(event){
this.style.backgroundColor="silver";
},false);
li.addEventListener("mouseout",function(event){
this.style.backgroundColor="transparent";
},false);
}else{
if(li.attachEvent){
li.attachEvent("onclick",function(event){
var _4206=arguments[0]||window.event;
_4206.cancelBubble=true;
_4206.returnValue=false;
var diffX=_4206.clientX;
var diffY=_4206.clientY;
var _4209=document.body.parentNode.scrollLeft;
var _420a=document.body.parentNode.scrollTop;
event.srcElement.menuItem.execute(diffX+_4209,diffY+_420a);
});
li.attachEvent("onmousedown",function(event){
event.cancelBubble=true;
event.returnValue=false;
});
li.attachEvent("onmouseup",function(event){
event.cancelBubble=true;
event.returnValue=false;
});
li.attachEvent("onmouseover",function(event){
event.srcElement.style.backgroundColor="silver";
});
li.attachEvent("onmouseout",function(event){
event.srcElement.style.backgroundColor="transparent";
});
}
}
}
};
MenuItem=function(label,_3f5b,_3f5c){
this.label=label;
this.iconUrl=_3f5b;
this.parentMenu=null;
this.action=_3f5c;
};
MenuItem.prototype.type="MenuItem";
MenuItem.prototype.isEnabled=function(){
return true;
};
MenuItem.prototype.getLabel=function(){
return this.label;
};
MenuItem.prototype.execute=function(x,y){
this.parentMenu.workflow.showMenu(null);
this.action(x,y);
};
Locator=function(){
};
Locator.prototype.type="Locator";
Locator.prototype.relocate=function(_3a8d){
};
ConnectionLocator=function(_3f69){
Locator.call(this);
this.connection=_3f69;
};
ConnectionLocator.prototype=new Locator;
ConnectionLocator.prototype.type="ConnectionLocator";
ConnectionLocator.prototype.getConnection=function(){
return this.connection;
};
ManhattenMidpointLocator=function(_3b8e){
ConnectionLocator.call(this,_3b8e);
};
ManhattenMidpointLocator.prototype=new ConnectionLocator;
ManhattenMidpointLocator.prototype.type="ManhattenMidpointLocator";
ManhattenMidpointLocator.prototype.relocate=function(_3b8f){
var conn=this.getConnection();
var p=new Point();
var _3b92=conn.getPoints();
var index=Math.floor((_3b92.getSize()-2)/2);
var p1=_3b92.get(index);
var p2=_3b92.get(index+1);
p.x=(p2.x-p1.x)/2+p1.x+5;
p.y=(p2.y-p1.y)/2+p1.y+5;
_3b8f.setPosition(p.x,p.y);
};
|
Increased the size of the Input and Outpur Ports
|
gulliver/js/ext/draw2d.js
|
Increased the size of the Input and Outpur Ports
|
<ide><path>ulliver/js/ext/draw2d.js
<ide> this.graphics.setStroke(this.stroke);
<ide> if(this.bgColor!=null){
<ide> this.graphics.setColor(this.bgColor.getHTMLStyle());
<del>this.graphics.fillOval(0,0,this.getWidth()-1,this.getHeight()-1);
<add>this.graphics.fillOval(0,0,this.getWidth()+2,this.getHeight()+2);
<ide> }
<ide> if(this.lineColor!=null){
<ide> this.graphics.setColor(this.lineColor.getHTMLStyle());
<del>this.graphics.drawOval(0,0,this.getWidth()-1,this.getHeight()-1);
<add>this.graphics.drawOval(0,0,this.getWidth()+2,this.getHeight()+2);
<ide> }
<ide> this.graphics.paint();
<ide> };
|
|
JavaScript
|
mit
|
b56928a62bb819e0791a78ceae28edea71fc4a63
| 0 |
apowers313/pigunit
|
// set java max heap size to 6GB. the default size (typically 128MB) dies on even the smallest test
/* TODO: don't overwrite previous _JAVA_OPTIONS */
require.paths = "{{moduleDir}}/node_modules";
process.env['_JAVA_OPTIONS'] = "-Xmx6144m -Dfile.encoding=UTF-8";
var pigHome = process.env.PIG_HOME;
var assert = require('assert');
assert.notStrictEqual (pigHome, undefined, "PIG_HOME environment variable does not seem to be set. It must point to your installation of Apache Pig.");
var scriptDirectory = "./";
var suiteName = "PigTest";
var fs = require('fs');
var path = require('path');
var java = require('java');
var pigJar = path.resolve(pigHome, 'pig.jar');
var pigunitJar = path.resolve(pigHome, 'pigunit.jar');
java.classpath.push(pigJar);
java.classpath.push(pigunitJar);
// setup arguments for PigTest
/* XXX: these intermediate variables are nice for debugging, but they can go away when validation is implemented */
var pigScript = "{{script}}";
var argsArray = [{{#strArray args}}{{/strArray}}];
var inputAlias = "{{inputAlias}}";
var inputArray = [{{#strArray input}}{{/strArray}}];
var outputAlias = "{{outputAlias}}";
var outputArray = [{{#strArray output}}{{/strArray}}];
var testName = "{{testDesc}}";
var timeoutOption = {{options.timeout}};
// convert args to Java arrays
var pigArgs = java.newArray("java.lang.String", argsArray);
var input = java.newArray("java.lang.String", inputArray);
var output = java.newArray("java.lang.String", outputArray);
var pigScript = path.resolve (scriptDirectory, pigScript);
// run test suite
describe(suiteName, function() {
this.timeout(timeoutOption);
// run test
it(testName, function(done) {
// verify that pig script exists
fs.exists(pigScript, function(exists) {
assert.strictEqual (exists, true, "couldn't find pig script");
// create a new pig test object
java.newInstance('org.apache.pig.pigunit.PigTest', pigScript, pigArgs, function(err, pigtest) {
// make sure the object was created okay
console.log (err);
assert.strictEqual (err, undefined, "could not create PigTest object");
assert.notStrictEqual (pigtest, null, "created PigTest object was null");
// run the pig test
pigtest.assertOutput(inputAlias, input, outputAlias, output, function(err, blah) {
assert.strictEqual (err, undefined, "PigTest assertOutput failed: actual output didn't match expected output");
done();
});
});
/* TODO: catch Java exceptions? */
});
});
});
|
support/pigunit-template.js
|
// set java max heap size to 6GB. the default size (typically 128MB) dies on even the smallest test
/* TODO: don't overwrite previous _JAVA_OPTIONS */
require.paths = "{{moduleDir}}/node_modules";
process.env['_JAVA_OPTIONS'] = "-Xmx6144m";
var pigHome = process.env.PIG_HOME;
var assert = require('assert');
assert.notStrictEqual (pigHome, undefined, "PIG_HOME environment variable does not seem to be set. It must point to your installation of Apache Pig.");
var scriptDirectory = "./";
var suiteName = "PigTest";
var fs = require('fs');
var path = require('path');
var java = require('java');
var pigJar = path.resolve(pigHome, 'pig.jar');
var pigunitJar = path.resolve(pigHome, 'pigunit.jar');
java.classpath.push(pigJar);
java.classpath.push(pigunitJar);
// setup arguments for PigTest
/* XXX: these intermediate variables are nice for debugging, but they can go away when validation is implemented */
var pigScript = "{{script}}";
var argsArray = [{{#strArray args}}{{/strArray}}];
var inputAlias = "{{inputAlias}}";
var inputArray = [{{#strArray input}}{{/strArray}}];
var outputAlias = "{{outputAlias}}";
var outputArray = [{{#strArray output}}{{/strArray}}];
var testName = "{{testDesc}}";
var timeoutOption = {{options.timeout}};
// convert args to Java arrays
var pigArgs = java.newArray("java.lang.String", argsArray);
var input = java.newArray("java.lang.String", inputArray);
var output = java.newArray("java.lang.String", outputArray);
var pigScript = path.resolve (scriptDirectory, pigScript);
// run test suite
describe(suiteName, function() {
this.timeout(timeoutOption);
// run test
it(testName, function(done) {
// verify that pig script exists
fs.exists(pigScript, function(exists) {
assert.strictEqual (exists, true, "couldn't find pig script");
// create a new pig test object
java.newInstance('org.apache.pig.pigunit.PigTest', pigScript, pigArgs, function(err, pigtest) {
// make sure the object was created okay
console.log (err);
assert.strictEqual (err, undefined, "could not create PigTest object");
assert.notStrictEqual (pigtest, null, "created PigTest object was null");
// run the pig test
pigtest.assertOutput(inputAlias, input, outputAlias, output, function(err, blah) {
assert.strictEqual (err, undefined, "PigTest assertOutput failed: actual output didn't match expected output");
done();
});
});
/* TODO: catch Java exceptions? */
});
});
});
|
enable to write .pu files in utf-8
|
support/pigunit-template.js
|
enable to write .pu files in utf-8
|
<ide><path>upport/pigunit-template.js
<ide> /* TODO: don't overwrite previous _JAVA_OPTIONS */
<ide> require.paths = "{{moduleDir}}/node_modules";
<ide>
<del>process.env['_JAVA_OPTIONS'] = "-Xmx6144m";
<add>process.env['_JAVA_OPTIONS'] = "-Xmx6144m -Dfile.encoding=UTF-8";
<ide> var pigHome = process.env.PIG_HOME;
<ide> var assert = require('assert');
<ide> assert.notStrictEqual (pigHome, undefined, "PIG_HOME environment variable does not seem to be set. It must point to your installation of Apache Pig.");
|
|
Java
|
apache-2.0
|
b73957591b694f071bcd612d7456034bc3f22845
| 0 |
NLeSC/Xenon,NLeSC/Xenon
|
/*
* Copyright 2013 Netherlands eScience Center
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.esciencecenter.xenon.adaptors.schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import java.io.OutputStream;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.esciencecenter.xenon.UnsupportedOperationException;
import nl.esciencecenter.xenon.XenonException;
import nl.esciencecenter.xenon.schedulers.JobDescription;
import nl.esciencecenter.xenon.schedulers.JobStatus;
import nl.esciencecenter.xenon.schedulers.NoSuchJobException;
import nl.esciencecenter.xenon.schedulers.NoSuchQueueException;
import nl.esciencecenter.xenon.schedulers.QueueStatus;
import nl.esciencecenter.xenon.schedulers.Scheduler;
import nl.esciencecenter.xenon.schedulers.SchedulerAdaptorDescription;
import nl.esciencecenter.xenon.schedulers.Streams;
import nl.esciencecenter.xenon.utils.LocalFileSystemUtils;
import nl.esciencecenter.xenon.utils.OutputReader;
public abstract class SchedulerTestParent {
public static final Logger LOGGER = LoggerFactory.getLogger(SchedulerTestParent.class);
private Scheduler scheduler;
private SchedulerAdaptorDescription description;
private SchedulerLocationConfig locationConfig;
@Before
public void setup() throws XenonException {
scheduler = setupScheduler();
description = setupDescription();
locationConfig = setupLocationConfig();
}
protected abstract SchedulerLocationConfig setupLocationConfig();
@After
public void cleanup() throws XenonException {
if (scheduler.isOpen()) {
scheduler.close();
}
}
public abstract Scheduler setupScheduler() throws XenonException;
private SchedulerAdaptorDescription setupDescription() throws XenonException {
String name = scheduler.getAdaptorName();
return Scheduler.getAdaptorDescription(name);
}
@Test
public void test_close() throws XenonException {
scheduler.close();
assertFalse(scheduler.isOpen());
}
@Test
public void test_getLocation() throws XenonException {
String location = scheduler.getLocation();
assertEquals(locationConfig.getLocation(), location);
}
@Test
public void test_isEmbedded() throws XenonException {
assertEquals(locationConfig.isEmbedded(), description.isEmbedded());
}
@Test
public void test_supportsBatch() throws XenonException {
assertEquals(locationConfig.supportsBatch(), description.supportsBatch());
}
@Test
public void test_supportsInteractive() throws XenonException {
assertEquals(locationConfig.supportsInteractive(), description.supportsInteractive());
}
private boolean contains(String[] options, String expected) {
if (options == null || options.length == 0) {
return false;
}
for (String s : options) {
if (expected == null) {
if (s == null) {
return true;
}
} else {
if (expected.equals(s)) {
return true;
}
}
}
return false;
}
private boolean unorderedEquals(String[] expected, String[] actual) {
if (expected.length != actual.length) {
return false;
}
for (String s : expected) {
if (!contains(actual, s)) {
return false;
}
}
for (String s : actual) {
if (!contains(expected, s)) {
return false;
}
}
return true;
}
private JobStatus waitUntilRunning(String jobID) throws XenonException {
return waitUntilRunning(jobID, locationConfig.getMaxWaitUntilRunning());
}
private JobStatus waitUntilRunning(String jobID, long maxTime) throws XenonException {
JobStatus status = scheduler.getJobStatus(jobID);
long deadline = System.currentTimeMillis() + maxTime;
while (!status.isRunning() && !status.isDone() && System.currentTimeMillis() < deadline) {
System.out.println("Current jobs: " + Arrays.toString(scheduler.getJobs()));
status = scheduler.waitUntilRunning(jobID, 1000);
}
return status;
}
private JobStatus waitUntilDone(String jobID) throws XenonException {
return waitUntilDone(jobID, locationConfig.getMaxWaintUntilDone());
}
private JobStatus waitUntilDone(String jobID, long maxTime) throws XenonException {
JobStatus status = scheduler.getJobStatus(jobID);
long deadline = System.currentTimeMillis() + maxTime;
while (!status.isDone() && System.currentTimeMillis() < deadline) {
System.out.println("Current jobs: " + Arrays.toString(scheduler.getJobs()));
status = scheduler.waitUntilDone(jobID, 1000);
}
return status;
}
private void cleanupJobs(String... jobIDs) throws XenonException {
if (jobIDs == null || jobIDs.length == 0) {
return;
}
JobStatus[] stats = new JobStatus[jobIDs.length];
for (int i = 0; i < jobIDs.length; i++) {
if (jobIDs[i] != null) {
stats[i] = scheduler.cancelJob(jobIDs[i]);
}
}
for (int i = 0; i < jobIDs.length; i++) {
if (stats[i] != null) {
if (!stats[i].isDone()) {
stats[i] = waitUntilDone(jobIDs[i]);
}
}
}
for (int i = 0; i < jobIDs.length; i++) {
if (stats[i] != null && !stats[i].isDone()) {
throw new XenonException("TEST", "Job " + jobIDs[i] + " not done yet!");
}
}
}
private void cleanupJob(String jobID) throws XenonException {
JobStatus status = null;
// Clean up the mess..
// try {
status = scheduler.cancelJob(jobID);
// } catch (Exception e) {
// LOGGER.warn("Failed to cancel job: " + jobID, e);
// System.out.println("Failed to cancel job: " + jobID + " " + e);
// e.printStackTrace();
// return;
// }
if (!status.isDone()) {
// try {
status = waitUntilDone(jobID);
// } catch (Exception e) {
// LOGGER.warn("Failed to wait for job: " + jobID, e);
// System.out.println("Failed to wait for job: " + jobID + " " + e);
// e.printStackTrace();
// return;
}
if (!status.isDone()) {
throw new XenonException("TEST", "Job " + jobID + " not done yet!");
}
}
@Test
public void test_getQueueNames() throws XenonException {
assertTrue(unorderedEquals(locationConfig.getQueueNames(), scheduler.getQueueNames()));
}
@Test
public void test_getDefaultQueueNames() throws XenonException {
assertEquals(locationConfig.getDefaultQueueName(), scheduler.getDefaultQueueName());
}
private JobDescription getSleepJob(String queue, int time) {
JobDescription job = new JobDescription();
job.setExecutable("/bin/sleep");
job.setArguments("" + time);
if (queue != null) {
job.setQueueName(queue);
}
return job;
}
@Test
public void test_sleep() throws XenonException {
assumeTrue(description.supportsBatch());
String jobID = scheduler.submitBatchJob(getSleepJob(null, 1));
JobStatus status = waitUntilDone(jobID);
assertTrue("Job is not done yet", status.isDone());
}
@Test
public void test_cancel() throws XenonException {
assumeTrue(description.supportsBatch());
String jobID = scheduler.submitBatchJob(getSleepJob(null, 240));
// Wait until the job is running.
JobStatus status = waitUntilRunning(jobID);
assertFalse("Job is already done", status.isDone());
assertTrue("Job is not running yet", status.isRunning());
status = scheduler.cancelJob(jobID);
if (!status.isDone()) {
// Wait up until the job is completely done
status = waitUntilDone(jobID);
}
assertTrue(status.isDone());
}
@Test
public void test_getJobsQueueNameEmpty() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 0);
// Submit job of 5 seconds to first queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs
String[] jobs = scheduler.getJobs();
// Our job should be part of this
assertTrue(contains(jobs, jobID));
// Clean up the mess.
cleanupJob(jobID);
}
@Test
public void test_getJobsQueueNameNull() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 0);
// Submit job of 5 seconds to first queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs
String[] jobs = scheduler.getJobs(new String[0]);
// Our job should be part of this
assertTrue(contains(jobs, jobID));
// Clean up the mess...
cleanupJob(jobID);
}
@Test
public void test_getJobsQueueNameCorrect() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 0);
// Submit it
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs
String[] jobs = scheduler.getJobs(queueNames[0]);
// Our job should be part of this
assertTrue(contains(jobs, jobID));
// Clean up the mess...
cleanupJob(jobID);
}
@Test
public void test_getJobsQueueNameOtherQueue() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 1);
// Submit job to one queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs for other queue
String[] jobs = scheduler.getJobs(queueNames[1]);
// Our job should NOT be part of this
assertFalse(contains(jobs, jobID));
// Clean up the mess...
cleanupJob(jobID);
}
@Test(expected = NoSuchQueueException.class)
public void test_getJobsQueueNameInCorrect() throws XenonException {
scheduler.getJobs("foobar");
}
@Test(expected = NoSuchJobException.class)
public void test_getJobStatus_unknownJob() throws XenonException {
scheduler.getJobStatus("aap");
}
@Test(expected = IllegalArgumentException.class)
public void test_getJobStatus_null() throws XenonException {
scheduler.getJobStatus(null);
}
@Test
public void test_getJobStatus_knownJob() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
// Submit job to one queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 1));
JobStatus status = scheduler.getJobStatus(jobID);
assertNotNull(status);
assertEquals(jobID, status.getJobIdentifier());
assertFalse(status.isDone());
// Clean up the mess...
cleanupJob(jobID);
}
@Test
public void test_getJobStatusses_noJobs() throws XenonException {
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses();
assertNotNull(result);
assertTrue(result.length == 0);
}
@Test
public void test_getJobStatusses_nonExistingJobs() throws XenonException {
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses("aap", "noot");
assertNotNull(result);
assertTrue(result.length == 2);
assertNotNull(result[0]);
assertEquals("aap", result[0].getJobIdentifier());
assertTrue(result[0].hasException());
assertNotNull(result[1]);
assertEquals("noot", result[1].getJobIdentifier());
assertTrue(result[1].hasException());
}
@Test
public void test_getJobStatusses_nonExistingJobsWithNull() throws XenonException {
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses("aap", null, "noot");
assertNotNull(result);
assertTrue(result.length == 3);
assertNotNull(result[0]);
assertEquals("aap", result[0].getJobIdentifier());
assertTrue(result[0].hasException());
assertNull(result[1]);
assertNotNull(result[2]);
assertEquals("noot", result[2].getJobIdentifier());
assertTrue(result[2].hasException());
}
@Test
public void test_getJobStatusses_existingJobs() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
// Submit two jobs to queue
String jobID1 = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
String jobID2 = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses(jobID1, jobID2);
assertNotNull(result);
assertTrue(result.length == 2);
assertNotNull(result[0]);
assertEquals(jobID1, result[0].getJobIdentifier());
assertFalse(result[0].isDone());
assertNotNull(result[1]);
assertEquals(jobID2, result[1].getJobIdentifier());
assertFalse(result[1].isDone());
// Clean up the mess...
cleanupJobs(jobID1, jobID2);
}
@Test(expected = IllegalArgumentException.class)
public void test_getQueueStatus_null() throws XenonException {
scheduler.getQueueStatus(null);
}
@Test(expected = NoSuchQueueException.class)
public void test_getQueueStatus_unknownQueue() throws XenonException {
scheduler.getQueueStatus("aap");
}
@Test
public void test_getQueueStatus_knownQueue() throws XenonException {
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
QueueStatus status = scheduler.getQueueStatus(queueNames[0]);
assertNotNull(status);
assertEquals(queueNames[0], status.getQueueName());
}
@Test(expected = IllegalArgumentException.class)
public void test_getQueueStatusses_null() throws XenonException {
scheduler.getQueueStatuses((String[]) null);
}
@Test
public void test_getQueueStatusses_empty() throws XenonException {
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
QueueStatus[] result = scheduler.getQueueStatuses(new String[0]);
assertNotNull(result);
assertTrue(queueNames.length == result.length);
for (int i = 0; i < queueNames.length; i++) {
assertNotNull(result[i]);
assertEquals(queueNames[i], result[i].getQueueName());
assertFalse(result[i].hasException());
}
}
@Test
public void test_getQueueStatusses_allQueues() throws XenonException {
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
QueueStatus[] result = scheduler.getQueueStatuses(queueNames);
assertNotNull(result);
assertTrue(queueNames.length == result.length);
for (int i = 0; i < queueNames.length; i++) {
assertNotNull(result[i]);
assertEquals(queueNames[i], result[i].getQueueName());
assertFalse(result[i].hasException());
}
}
@Test
public void test_getQueueStatusses_withNull() throws XenonException {
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 1);
String[] alt = new String[queueNames.length + 1];
alt[0] = queueNames[0];
alt[1] = null;
for (int i = 1; i < queueNames.length; i++) {
alt[i + 1] = queueNames[i];
}
QueueStatus[] result = scheduler.getQueueStatuses(alt);
assertNotNull(result);
assertTrue(alt.length == result.length);
assertNotNull(result[0]);
assertEquals(queueNames[0], result[0].getQueueName());
assertNull(result[1]);
for (int i = 1; i < queueNames.length; i++) {
assertNotNull(result[i + 1]);
assertEquals(queueNames[i], result[i + 1].getQueueName());
assertFalse(result[i + 1].hasException());
}
}
@Test(expected = UnsupportedOperationException.class)
public void test_interactiveJob_notSupported_throwsException() throws XenonException {
assumeFalse(description.supportsInteractive());
JobDescription job = new JobDescription();
job.setExecutable("/bin/cat");
scheduler.submitInteractiveJob(job);
}
@Test
public void test_interactiveJob() throws Exception {
assumeTrue(description.supportsInteractive());
// Do not run this test on windows, as /bin/cat does not exist
assumeFalse(scheduler.getAdaptorName().equals("local") && LocalFileSystemUtils.isWindows());
JobDescription job = new JobDescription();
job.setExecutable("/bin/cat");
Streams streams = scheduler.submitInteractiveJob(job);
OutputReader out = new OutputReader(streams.getStdout());
OutputReader err = new OutputReader(streams.getStderr());
OutputStream stdin = streams.getStdin();
stdin.write("Hello World\n".getBytes());
stdin.write("Goodbye World\n".getBytes());
stdin.close();
out.waitUntilFinished();
err.waitUntilFinished();
assertEquals("Hello World\nGoodbye World\n", out.getResultAsString());
cleanupJob(streams.getJobIdentifier());
}
@Test
public void test_interactiveJob_windows() throws Exception {
assumeTrue(description.supportsInteractive());
// Only runthis test on windows and in the local adaptor
assumeTrue(scheduler.getAdaptorName().equals("local") && LocalFileSystemUtils.isWindows());
JobDescription job = new JobDescription();
job.setExecutable("C:\\Windows\\System32\\more.exe");
Streams streams = scheduler.submitInteractiveJob(job);
OutputReader out = new OutputReader(streams.getStdout());
OutputReader err = new OutputReader(streams.getStderr());
OutputStream stdin = streams.getStdin();
stdin.write("Hello World\n".getBytes());
stdin.write("Goodbye World\n".getBytes());
stdin.close();
out.waitUntilFinished();
err.waitUntilFinished();
assertEquals("Hello World\nGoodbye World\n", out.getResultAsString());
cleanupJob(streams.getJobIdentifier());
}
/*
* @Test(expected=XenonException.class) public void test_waitUntilDone_unknownJobID_throwsException() throws XenonException {
* scheduler.waitUntilDone("foobar", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilDone_nullJobID_throwsException() throws XenonException {
* scheduler.waitUntilDone(null, 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilDone_emptyJobID_throwsException() throws XenonException {
* scheduler.waitUntilDone("", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilDone_invalidTimeout_throwsException() throws XenonException {
* scheduler.waitUntilDone("foobar", -1000); }
*
* @Test(expected=XenonException.class) public void test_waitUntilRunning_unknownJobID_throwsException() throws XenonException {
* scheduler.waitUntilRunning("foobar", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilRunning_nullJobID_throwsException() throws XenonException {
* scheduler.waitUntilRunning(null, 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilRunning_emptyJobID_throwsException() throws XenonException {
* scheduler.waitUntilRunning("", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilRunning_invalidTimeout_throwsException() throws XenonException {
* scheduler.waitUntilRunning("foobar", -1000); }
*
* @Test(expected=XenonException.class) public void test_cancel_unknownJobID_throwsException() throws XenonException { scheduler.cancelJob("foobar"); }
*
* @Test(expected=IllegalArgumentException.class) public void test_cancel_nullJobID_throwsException() throws XenonException { scheduler.cancelJob(null); }
*
* @Test(expected=IllegalArgumentException.class) public void test_cancel_emptyJobID_throwsException() throws XenonException { scheduler.cancelJob(""); }
*/
// TODO: check illegalargument exceptions
}
|
src/integrationTest/java/nl/esciencecenter/xenon/adaptors/schedulers/SchedulerTestParent.java
|
/*
* Copyright 2013 Netherlands eScience Center
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.esciencecenter.xenon.adaptors.schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import java.io.OutputStream;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.esciencecenter.xenon.UnsupportedOperationException;
import nl.esciencecenter.xenon.XenonException;
import nl.esciencecenter.xenon.schedulers.JobDescription;
import nl.esciencecenter.xenon.schedulers.JobStatus;
import nl.esciencecenter.xenon.schedulers.NoSuchJobException;
import nl.esciencecenter.xenon.schedulers.NoSuchQueueException;
import nl.esciencecenter.xenon.schedulers.QueueStatus;
import nl.esciencecenter.xenon.schedulers.Scheduler;
import nl.esciencecenter.xenon.schedulers.SchedulerAdaptorDescription;
import nl.esciencecenter.xenon.schedulers.Streams;
import nl.esciencecenter.xenon.utils.LocalFileSystemUtils;
import nl.esciencecenter.xenon.utils.OutputReader;
public abstract class SchedulerTestParent {
public static final Logger LOGGER = LoggerFactory.getLogger(SchedulerTestParent.class);
private Scheduler scheduler;
private SchedulerAdaptorDescription description;
private SchedulerLocationConfig locationConfig;
@Before
public void setup() throws XenonException {
scheduler = setupScheduler();
description = setupDescription();
locationConfig = setupLocationConfig();
}
protected abstract SchedulerLocationConfig setupLocationConfig();
@After
public void cleanup() throws XenonException {
if (scheduler.isOpen()) {
scheduler.close();
}
}
public abstract Scheduler setupScheduler() throws XenonException;
private SchedulerAdaptorDescription setupDescription() throws XenonException {
String name = scheduler.getAdaptorName();
return Scheduler.getAdaptorDescription(name);
}
@Test
public void test_close() throws XenonException {
scheduler.close();
assertFalse(scheduler.isOpen());
}
@Test
public void test_getLocation() throws XenonException {
String location = scheduler.getLocation();
assertEquals(locationConfig.getLocation(), location);
}
@Test
public void test_isEmbedded() throws XenonException {
assertEquals(locationConfig.isEmbedded(), description.isEmbedded());
}
@Test
public void test_supportsBatch() throws XenonException {
assertEquals(locationConfig.supportsBatch(), description.supportsBatch());
}
@Test
public void test_supportsInteractive() throws XenonException {
assertEquals(locationConfig.supportsInteractive(), description.supportsInteractive());
}
private boolean contains(String[] options, String expected) {
if (options == null || options.length == 0) {
return false;
}
for (String s : options) {
if (expected == null) {
if (s == null) {
return true;
}
} else {
if (expected.equals(s)) {
return true;
}
}
}
return false;
}
private boolean unorderedEquals(String[] expected, String[] actual) {
if (expected.length != actual.length) {
return false;
}
for (String s : expected) {
if (!contains(actual, s)) {
return false;
}
}
for (String s : actual) {
if (!contains(expected, s)) {
return false;
}
}
return true;
}
private JobStatus waitUntilRunning(String jobID) throws XenonException {
return waitUntilRunning(jobID, locationConfig.getMaxWaitUntilRunning());
}
private JobStatus waitUntilRunning(String jobID, long maxTime) throws XenonException {
JobStatus status = scheduler.getJobStatus(jobID);
long deadline = System.currentTimeMillis() + maxTime;
while (!status.isRunning() && !status.isDone() && System.currentTimeMillis() < deadline) {
System.out.println("Current jobs: " + Arrays.toString(scheduler.getJobs()));
status = scheduler.waitUntilRunning(jobID, 1000);
}
return status;
}
private JobStatus waitUntilDone(String jobID) throws XenonException {
return waitUntilDone(jobID, locationConfig.getMaxWaintUntilDone());
}
private JobStatus waitUntilDone(String jobID, long maxTime) throws XenonException {
JobStatus status = scheduler.getJobStatus(jobID);
long deadline = System.currentTimeMillis() + maxTime;
while (!status.isDone() && System.currentTimeMillis() < deadline) {
System.out.println("Current jobs: " + Arrays.toString(scheduler.getJobs()));
status = scheduler.waitUntilDone(jobID, 1000);
}
return status;
}
private void cleanupJobs(String... jobIDs) throws XenonException {
if (jobIDs == null || jobIDs.length == 0) {
return;
}
JobStatus[] stats = new JobStatus[jobIDs.length];
for (int i = 0; i < jobIDs.length; i++) {
if (jobIDs[i] != null) {
stats[i] = scheduler.cancelJob(jobIDs[i]);
}
}
for (int i = 0; i < jobIDs.length; i++) {
if (stats[i] != null) {
if (!stats[i].isDone()) {
stats[i] = waitUntilDone(jobIDs[i]);
}
}
}
for (int i = 0; i < jobIDs.length; i++) {
if (stats[i] != null && !stats[i].isDone()) {
throw new XenonException("TEST", "Job " + jobIDs[i] + " not done yet!");
}
}
}
private void cleanupJob(String jobID) throws XenonException {
JobStatus status = null;
// Clean up the mess..
// try {
status = scheduler.cancelJob(jobID);
// } catch (Exception e) {
// LOGGER.warn("Failed to cancel job: " + jobID, e);
// System.out.println("Failed to cancel job: " + jobID + " " + e);
// e.printStackTrace();
// return;
// }
if (!status.isDone()) {
// try {
status = waitUntilDone(jobID);
// } catch (Exception e) {
// LOGGER.warn("Failed to wait for job: " + jobID, e);
// System.out.println("Failed to wait for job: " + jobID + " " + e);
// e.printStackTrace();
// return;
}
if (!status.isDone()) {
throw new XenonException("TEST", "Job " + jobID + " not done yet!");
}
}
@Test
public void test_getQueueNames() throws XenonException {
assertTrue(unorderedEquals(locationConfig.getQueueNames(), scheduler.getQueueNames()));
}
@Test
public void test_getDefaultQueueNames() throws XenonException {
assertEquals(locationConfig.getDefaultQueueName(), scheduler.getDefaultQueueName());
}
private JobDescription getSleepJob(String queue, int time) {
JobDescription job = new JobDescription();
job.setExecutable("/bin/sleep");
job.setArguments("" + time);
if (queue != null) {
job.setQueueName(queue);
}
return job;
}
@Test
public void test_sleep() throws XenonException {
assumeTrue(description.supportsBatch());
String jobID = scheduler.submitBatchJob(getSleepJob(null, 1));
JobStatus status = waitUntilDone(jobID);
assertTrue("Job is not done yet", status.isDone());
}
@Test
public void test_cancel() throws XenonException {
assumeTrue(description.supportsBatch());
String jobID = scheduler.submitBatchJob(getSleepJob(null, 240));
// Wait until the job is running.
JobStatus status = waitUntilRunning(jobID);
assertFalse("Job is already done", status.isDone());
assertTrue("Job is not running yet", status.isRunning());
status = scheduler.cancelJob(jobID);
if (!status.isDone()) {
// Wait up until the job is completely done
status = waitUntilDone(jobID);
}
assertTrue(status.isDone());
}
@Test
public void test_getJobsQueueNameEmpty() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 0);
// Submit job of 5 seconds to first queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs
String[] jobs = scheduler.getJobs();
// Our job should be part of this
assertTrue(contains(jobs, jobID));
// Clean up the mess.
cleanupJob(jobID);
}
@Test
public void test_getJobsQueueNameNull() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 0);
// Submit job of 5 seconds to first queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs
String[] jobs = scheduler.getJobs(new String[0]);
// Our job should be part of this
assertTrue(contains(jobs, jobID));
// Clean up the mess...
cleanupJob(jobID);
}
@Test
public void test_getJobsQueueNameCorrect() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 0);
// Submit it
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs
String[] jobs = scheduler.getJobs(queueNames[0]);
// Our job should be part of this
assertTrue(contains(jobs, jobID));
// Clean up the mess...
cleanupJob(jobID);
}
@Test
public void test_getJobsQueueNameOtherQueue() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 1);
// Submit job to one queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Retrieve all jobs for other queue
String[] jobs = scheduler.getJobs(queueNames[1]);
// Our job should NOT be part of this
assertFalse(contains(jobs, jobID));
// Clean up the mess...
cleanupJob(jobID);
}
@Test(expected = NoSuchQueueException.class)
public void test_getJobsQueueNameInCorrect() throws XenonException {
scheduler.getJobs("foobar");
}
@Test(expected = NoSuchJobException.class)
public void test_getJobStatus_unknownJob() throws XenonException {
scheduler.getJobStatus("aap");
}
@Test(expected = IllegalArgumentException.class)
public void test_getJobStatus_null() throws XenonException {
scheduler.getJobStatus(null);
}
@Test
public void test_getJobStatus_knownJob() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
// Submit job to one queue
String jobID = scheduler.submitBatchJob(getSleepJob(queueNames[0], 1));
JobStatus status = scheduler.getJobStatus(jobID);
assertNotNull(status);
assertEquals(jobID, status.getJobIdentifier());
assertFalse(status.isDone());
// Clean up the mess...
cleanupJob(jobID);
}
@Test
public void test_getJobStatusses_noJobs() throws XenonException {
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses();
assertNotNull(result);
assertTrue(result.length == 0);
}
@Test
public void test_getJobStatusses_nonExistingJobs() throws XenonException {
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses("aap", "noot");
assertNotNull(result);
assertTrue(result.length == 2);
assertNotNull(result[0]);
assertEquals("aap", result[0].getJobIdentifier());
assertTrue(result[0].hasException());
assertNotNull(result[1]);
assertEquals("noot", result[1].getJobIdentifier());
assertTrue(result[1].hasException());
}
@Test
public void test_getJobStatusses_nonExistingJobsWithNull() throws XenonException {
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses("aap", null, "noot");
assertNotNull(result);
assertTrue(result.length == 3);
assertNotNull(result[0]);
assertEquals("aap", result[0].getJobIdentifier());
assertTrue(result[0].hasException());
assertNull(result[1]);
assertNotNull(result[2]);
assertEquals("noot", result[2].getJobIdentifier());
assertTrue(result[2].hasException());
}
@Test
public void test_getJobStatusses_existingJobs() throws XenonException {
assumeTrue(description.supportsBatch());
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
// Submit two jobs to queue
String jobID1 = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
String jobID2 = scheduler.submitBatchJob(getSleepJob(queueNames[0], 5));
// Get the status of no jobs
JobStatus[] result = scheduler.getJobStatuses(jobID1, jobID2);
assertNotNull(result);
assertTrue(result.length == 2);
assertNotNull(result[0]);
assertEquals(jobID1, result[0].getJobIdentifier());
assertFalse(result[0].isDone());
assertNotNull(result[1]);
assertEquals(jobID2, result[1].getJobIdentifier());
assertFalse(result[1].isDone());
// Clean up the mess...
cleanupJobs(jobID1, jobID2);
}
@Test(expected = IllegalArgumentException.class)
public void test_getQueueStatus_null() throws XenonException {
scheduler.getQueueStatus(null);
}
@Test(expected = NoSuchQueueException.class)
public void test_getQueueStatus_unknownQueue() throws XenonException {
scheduler.getQueueStatus("aap");
}
@Test
public void test_getQueueStatus_knownQueue() throws XenonException {
// Get the available queues
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
QueueStatus status = scheduler.getQueueStatus(queueNames[0]);
assertNotNull(status);
assertEquals(queueNames[0], status.getQueueName());
}
@Test(expected = IllegalArgumentException.class)
public void test_getQueueStatusses_null() throws XenonException {
scheduler.getQueueStatuses((String[]) null);
}
@Test
public void test_getQueueStatusses_empty() throws XenonException {
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
QueueStatus[] result = scheduler.getQueueStatuses(new String[0]);
assertNotNull(result);
assertTrue(queueNames.length == result.length);
for (int i = 0; i < queueNames.length; i++) {
assertNotNull(result[i]);
assertEquals(queueNames[i], result[i].getQueueName());
assertFalse(result[i].hasException());
}
}
@Test
public void test_getQueueStatusses_allQueues() throws XenonException {
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length >= 1);
QueueStatus[] result = scheduler.getQueueStatuses(queueNames);
assertNotNull(result);
assertTrue(queueNames.length == result.length);
for (int i = 0; i < queueNames.length; i++) {
assertNotNull(result[i]);
assertEquals(queueNames[i], result[i].getQueueName());
assertFalse(result[i].hasException());
}
}
@Test
public void test_getQueueStatusses_withNull() throws XenonException {
String[] queueNames = locationConfig.getQueueNames();
assumeTrue(queueNames != null);
assumeTrue(queueNames.length > 1);
String[] alt = new String[queueNames.length + 1];
alt[0] = queueNames[0];
alt[1] = null;
for (int i = 1; i < queueNames.length; i++) {
alt[i + 1] = queueNames[i];
}
QueueStatus[] result = scheduler.getQueueStatuses(alt);
assertNotNull(result);
assertTrue(alt.length == result.length);
assertNotNull(result[0]);
assertEquals(queueNames[0], result[0].getQueueName());
assertNull(result[1]);
for (int i = 1; i < queueNames.length; i++) {
assertNotNull(result[i + 1]);
assertEquals(queueNames[i], result[i + 1].getQueueName());
assertFalse(result[i + 1].hasException());
}
}
@Test(expected = UnsupportedOperationException.class)
public void test_interactiveJob_notSupported_throwsException() throws XenonException {
assumeFalse(description.supportsInteractive());
JobDescription job = new JobDescription();
job.setExecutable("/bin/cat");
scheduler.submitInteractiveJob(job);
}
@Test
public void test_interactiveJob() throws Exception {
assumeTrue(description.supportsInteractive());
// Do not run this test on windows, as /bin/cat does not exist
assumeFalse(scheduler.getAdaptorName().equals("local") && LocalFileSystemUtils.isWindows());
JobDescription job = new JobDescription();
job.setExecutable("/bin/cat");
Streams streams = scheduler.submitInteractiveJob(job);
OutputReader out = new OutputReader(streams.getStdout());
OutputReader err = new OutputReader(streams.getStderr());
OutputStream stdin = streams.getStdin();
stdin.write("Hello World\n".getBytes());
stdin.write("Goodbye World\n".getBytes());
stdin.close();
out.waitUntilFinished();
err.waitUntilFinished();
assertEquals("Hello World\nGoodbye World\n", out.getResultAsString());
cleanupJob(streams.getJobIdentifier());
}
@Test
public void test_interactiveJob_windows() throws Exception {
assumeTrue(description.supportsInteractive());
// Only runthis test on windows and in the local adaptor
assumeTrue(scheduler.getAdaptorName().equals("local") && LocalFileSystemUtils.isWindows());
JobDescription job = new JobDescription();
job.setExecutable("more");
Streams streams = scheduler.submitInteractiveJob(job);
OutputReader out = new OutputReader(streams.getStdout());
OutputReader err = new OutputReader(streams.getStderr());
OutputStream stdin = streams.getStdin();
stdin.write("Hello World\n".getBytes());
stdin.write("Goodbye World\n".getBytes());
stdin.close();
out.waitUntilFinished();
err.waitUntilFinished();
assertEquals("Hello World\nGoodbye World\n", out.getResultAsString());
cleanupJob(streams.getJobIdentifier());
}
/*
* @Test(expected=XenonException.class) public void test_waitUntilDone_unknownJobID_throwsException() throws XenonException {
* scheduler.waitUntilDone("foobar", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilDone_nullJobID_throwsException() throws XenonException {
* scheduler.waitUntilDone(null, 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilDone_emptyJobID_throwsException() throws XenonException {
* scheduler.waitUntilDone("", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilDone_invalidTimeout_throwsException() throws XenonException {
* scheduler.waitUntilDone("foobar", -1000); }
*
* @Test(expected=XenonException.class) public void test_waitUntilRunning_unknownJobID_throwsException() throws XenonException {
* scheduler.waitUntilRunning("foobar", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilRunning_nullJobID_throwsException() throws XenonException {
* scheduler.waitUntilRunning(null, 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilRunning_emptyJobID_throwsException() throws XenonException {
* scheduler.waitUntilRunning("", 5*1000); }
*
* @Test(expected=IllegalArgumentException.class) public void test_waitUntilRunning_invalidTimeout_throwsException() throws XenonException {
* scheduler.waitUntilRunning("foobar", -1000); }
*
* @Test(expected=XenonException.class) public void test_cancel_unknownJobID_throwsException() throws XenonException { scheduler.cancelJob("foobar"); }
*
* @Test(expected=IllegalArgumentException.class) public void test_cancel_nullJobID_throwsException() throws XenonException { scheduler.cancelJob(null); }
*
* @Test(expected=IllegalArgumentException.class) public void test_cancel_emptyJobID_throwsException() throws XenonException { scheduler.cancelJob(""); }
*/
// TODO: check illegalargument exceptions
}
|
Testing...
|
src/integrationTest/java/nl/esciencecenter/xenon/adaptors/schedulers/SchedulerTestParent.java
|
Testing...
|
<ide><path>rc/integrationTest/java/nl/esciencecenter/xenon/adaptors/schedulers/SchedulerTestParent.java
<ide> assumeTrue(scheduler.getAdaptorName().equals("local") && LocalFileSystemUtils.isWindows());
<ide>
<ide> JobDescription job = new JobDescription();
<del> job.setExecutable("more");
<add> job.setExecutable("C:\\Windows\\System32\\more.exe");
<ide>
<ide> Streams streams = scheduler.submitInteractiveJob(job);
<ide>
|
|
Java
|
apache-2.0
|
63c87f11f368f22f7cda4baeb64d30137028be7e
| 0 |
apache/juddi-scout,apache/juddi-scout
|
src/java/org/apache/ws/scout/registry/infomodel/SlotImpl.java
|
/*
* JBoss, the OpenSource J2EE webOS
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.apache.ws.scout.registry.infomodel;
import javax.xml.registry.infomodel.Slot;
import javax.xml.registry.JAXRException;
import javax.xml.registry.LifeCycleManager;
import java.util.Collection;
/**
* Implements Jaxr API
*
* @author <mailto:[email protected]>Anil Saldhana
* @since Nov 20, 2004
*/
public class SlotImpl implements Slot
{
private String slotType;
private String name;
private Collection values;
private LifeCycleManager lcm;
public SlotImpl(LifeCycleManager lifeCycleManager)
{
lcm = lifeCycleManager;
}
public String getName() throws JAXRException
{
return name;
}
public String getSlotType() throws JAXRException
{
return slotType;
}
public Collection getValues() throws JAXRException
{
return values;
}
public void setName(String s) throws JAXRException
{
name = s;
}
public void setSlotType(String s) throws JAXRException
{
slotType = s;
}
public void setValues(Collection collection) throws JAXRException
{
values = collection;
}
}
|
Delete the SlotImpl file as IDE screwed up license.
git-svn-id: d8c918df28636d4b45373672baad2da0d7b7f5b1@122974 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/ws/scout/registry/infomodel/SlotImpl.java
|
Delete the SlotImpl file as IDE screwed up license.
|
<ide><path>rc/java/org/apache/ws/scout/registry/infomodel/SlotImpl.java
<del>/*
<del> * JBoss, the OpenSource J2EE webOS
<del> *
<del> * Distributable under LGPL license.
<del> * See terms of license at gnu.org.
<del> */
<del>package org.apache.ws.scout.registry.infomodel;
<del>
<del>import javax.xml.registry.infomodel.Slot;
<del>import javax.xml.registry.JAXRException;
<del>import javax.xml.registry.LifeCycleManager;
<del>import java.util.Collection;
<del>
<del>/**
<del> * Implements Jaxr API
<del> *
<del> * @author <mailto:[email protected]>Anil Saldhana
<del> * @since Nov 20, 2004
<del> */
<del>public class SlotImpl implements Slot
<del>{
<del> private String slotType;
<del> private String name;
<del> private Collection values;
<del> private LifeCycleManager lcm;
<del>
<del> public SlotImpl(LifeCycleManager lifeCycleManager)
<del> {
<del> lcm = lifeCycleManager;
<del> }
<del> public String getName() throws JAXRException
<del> {
<del> return name;
<del> }
<del>
<del> public String getSlotType() throws JAXRException
<del> {
<del> return slotType;
<del> }
<del>
<del> public Collection getValues() throws JAXRException
<del> {
<del> return values;
<del> }
<del>
<del> public void setName(String s) throws JAXRException
<del> {
<del> name = s;
<del> }
<del>
<del> public void setSlotType(String s) throws JAXRException
<del> {
<del> slotType = s;
<del> }
<del>
<del> public void setValues(Collection collection) throws JAXRException
<del> {
<del> values = collection;
<del> }
<del>}
|
||
Java
|
apache-2.0
|
6e19b74744e2dd45993593edc4efdf731e4f4892
| 0 |
benchdoos/WeblocOpener,benchdoos/WeblocOpener,benchdoos/WeblocOpener
|
/*
* (C) Copyright 2019. Eugene Zrazhevsky and others.
* 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.
* Contributors:
* Eugene Zrazhevsky <[email protected]>
*/
package com.github.benchdoos.weblocopener.gui;
import com.github.benchdoos.jcolorful.core.JColorful;
import com.github.benchdoos.weblocopener.core.Translation;
import com.github.benchdoos.weblocopener.core.constants.ApplicationConstants;
import com.github.benchdoos.weblocopener.core.constants.StringConstants;
import com.github.benchdoos.weblocopener.gui.panels.*;
import com.github.benchdoos.weblocopener.preferences.PreferencesManager;
import com.github.benchdoos.weblocopener.service.Analyzer;
import com.github.benchdoos.weblocopener.service.UrlsProceed;
import com.github.benchdoos.weblocopener.utils.Converter;
import com.github.benchdoos.weblocopener.utils.FrameUtils;
import com.github.benchdoos.weblocopener.utils.Logging;
import com.github.benchdoos.weblocopener.utils.UserUtils;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.TooManyListenersException;
public class SettingsDialog extends JFrame implements Translatable {
private static final Logger log = LogManager.getLogger(Logging.getCurrentClassName());
private Timer settingsSavedTimer = null;
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JButton aboutButton;
private JScrollPane scrollpane;
private JList<SettingsPanel> settingsList;
private JPanel scrollPaneContent;
private JButton buttonApply;
private JLabel settingsSavedLabel;
private JButton donatePaypalButton;
private JLabel dragAndDropNotice;
private BrowserSetterPanel browserSetterPanel;
private MainSetterPanel mainSetterPanel;
private AppearanceSetterPanel appearanceSetterPanel;
private LocaleSetterPanel localeSetterPanel;
public SettingsDialog() {
$$$setupUI$$$();
log.debug("Creating settings dialog.");
initGui();
log.debug("Settings dialog created.");
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(3, 2, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(2, 5, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new GridConstraints(2, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2, new GridConstraints(1, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
this.$$$loadButtonText$$$(buttonOK, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonOk"));
panel2.add(buttonOK, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
this.$$$loadButtonText$$$(buttonCancel, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonCancel"));
panel2.add(buttonCancel, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonApply = new JButton();
this.$$$loadButtonText$$$(buttonApply, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonApply"));
panel2.add(buttonApply, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
aboutButton = new JButton();
this.$$$loadButtonText$$$(aboutButton, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonAbout"));
panel1.add(aboutButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
dragAndDropNotice = new JLabel();
dragAndDropNotice.setForeground(new Color(-6316129));
this.$$$loadLabelText$$$(dragAndDropNotice, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("dragAndDropNotice"));
panel1.add(dragAndDropNotice, new GridConstraints(0, 0, 1, 5, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
settingsSavedLabel = new JLabel();
settingsSavedLabel.setForeground(new Color(-16732650));
this.$$$loadLabelText$$$(settingsSavedLabel, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("settingsSaved"));
panel1.add(settingsSavedLabel, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
donatePaypalButton = new JButton();
donatePaypalButton.setBorderPainted(false);
donatePaypalButton.setContentAreaFilled(false);
donatePaypalButton.setIcon(new ImageIcon(getClass().getResource("/images/donate16.png")));
donatePaypalButton.setIconTextGap(0);
donatePaypalButton.setMargin(new Insets(0, 0, 0, 0));
donatePaypalButton.setOpaque(false);
donatePaypalButton.setText("");
panel1.add(donatePaypalButton, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer2 = new Spacer();
contentPane.add(spacer2, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final JSplitPane splitPane1 = new JSplitPane();
contentPane.add(splitPane1, new GridConstraints(0, 0, 2, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, 200), null, 0, false));
final JScrollPane scrollPane1 = new JScrollPane();
scrollPane1.setMinimumSize(new Dimension(128, 15));
splitPane1.setLeftComponent(scrollPane1);
settingsList = new JList();
settingsList.setSelectionMode(0);
scrollPane1.setViewportView(settingsList);
scrollpane = new JScrollPane();
splitPane1.setRightComponent(scrollpane);
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));
scrollpane.setViewportView(panel3);
panel3.add(scrollPaneContent, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final Spacer spacer3 = new Spacer();
panel3.add(spacer3, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
private void $$$loadLabelText$$$(JLabel component, String text) {
StringBuffer result = new StringBuffer();
boolean haveMnemonic = false;
char mnemonic = '\0';
int mnemonicIndex = -1;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '&') {
i++;
if (i == text.length()) break;
if (!haveMnemonic && text.charAt(i) != '&') {
haveMnemonic = true;
mnemonic = text.charAt(i);
mnemonicIndex = result.length();
}
}
result.append(text.charAt(i));
}
component.setText(result.toString());
if (haveMnemonic) {
component.setDisplayedMnemonic(mnemonic);
component.setDisplayedMnemonicIndex(mnemonicIndex);
}
}
/**
* @noinspection ALL
*/
private void $$$loadButtonText$$$(AbstractButton component, String text) {
StringBuffer result = new StringBuffer();
boolean haveMnemonic = false;
char mnemonic = '\0';
int mnemonicIndex = -1;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '&') {
i++;
if (i == text.length()) break;
if (!haveMnemonic && text.charAt(i) != '&') {
haveMnemonic = true;
mnemonic = text.charAt(i);
mnemonicIndex = result.length();
}
}
result.append(text.charAt(i));
}
component.setText(result.toString());
if (haveMnemonic) {
component.setMnemonic(mnemonic);
component.setDisplayedMnemonicIndex(mnemonicIndex);
}
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
private void createUIComponents() {
scrollPaneContent = new JPanel();
scrollPaneContent.setLayout(new GridLayout());
}
private void initDropTarget() {
final ImageIcon rickAndMortyIcon = new ImageIcon(Toolkit.getDefaultToolkit()
.getImage(getClass().getResource("/images/easter/rickAndMorty.gif")));
final DropTarget dropTarget = new DropTarget() {
@Override
public synchronized void drop(DropTargetDropEvent evt) {
onDrop(evt);
}
private void onDrop(DropTargetDropEvent evt) {
Translation translation = new Translation("SettingsDialogBundle");
try {
contentPane.setBorder(null);
evt.acceptDrop(DnDConstants.ACTION_COPY);
final Object transferData = evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
List<?> list = (List<?>) transferData;
ArrayList<File> files = new ArrayList<>(list.size());
int easterCounter = 0;
for (Object o : list) {
if (o instanceof File) {
File file = (File) o;
try {
if (FilenameUtils.removeExtension(file.getName()).toLowerCase().contains("rick and morty")) {
if (easterCounter == 0) {
showRickAndMortyEaster();
easterCounter++;
}
}
} catch (Exception e) {
log.warn("Rick and Morty easter egg is broken", e);
}
final String fileExtension = Analyzer.getFileExtension(file);
if (fileExtension.equalsIgnoreCase(ApplicationConstants.URL_FILE_EXTENSION)
|| fileExtension.equalsIgnoreCase(ApplicationConstants.DESKTOP_FILE_EXTENSION)) {
try {
files.add(Converter.convert(file, ApplicationConstants.WEBLOC_FILE_EXTENSION));
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
log.warn("Could not delete file: {}", file, e);
}
} catch (IOException e) {
log.warn("Could not convert *.{} to *.webloc file: {}", fileExtension, file, e);
}
} else if (fileExtension.equalsIgnoreCase(ApplicationConstants.WEBLOC_FILE_EXTENSION)) {
try {
files.add(Converter.convert(file, PreferencesManager.getConverterExportExtension()));
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
log.warn("Could not delete file: {}", file, e);
}
} catch (IOException e) {
log.warn("Could not convert *.webloc to *.{} file: {}", PreferencesManager.getConverterExportExtension(), file, e);
}
}
}
}
if (files.size() == list.size()) {
UserUtils.showTrayMessage(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME,
translation.getTranslatedString("allFilesSuccessfullyConverted")
+ files.size() + "/" + list.size(), TrayIcon.MessageType.INFO);
} else {
UserUtils.showTrayMessage(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME,
translation.getTranslatedString("someFilesFailedToConvert")
+ files.size() + "/" + list.size(), TrayIcon.MessageType.WARNING);
}
} catch (Exception ex) {
log.warn("Can not open files from drop", ex);
UserUtils.showTrayMessage(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME,
translation.getTranslatedString("couldNotConvertFiles"),
TrayIcon.MessageType.ERROR);
}
}
private void showRickAndMortyEaster() {
log.info("Look! This user has found an easter egg (Rick and Morty). Good job!");
JFrame frame = new JFrame(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME);
frame.setLayout(new GridLayout());
JLabel label = new JLabel();
label.setIcon(rickAndMortyIcon);
frame.add(label);
frame.setUndecorated(true);
frame.setSize(500, 281);
frame.setResizable(false);
frame.setLocation(FrameUtils.getFrameOnCenterLocationPoint(frame));
Timer timer = new Timer(5000, e -> frame.dispose());
timer.setRepeats(false);
timer.start();
frame.setVisible(true);
}
};
contentPane.setDropTarget(dropTarget);
try {
dropTarget.addDropTargetListener(new DropTargetAdapter() {
@Override
public void dragEnter(DropTargetDragEvent dtde) {
contentPane.setBorder(BorderFactory.createLineBorder(Color.RED));
super.dragEnter(dtde);
}
@Override
public void dragExit(DropTargetEvent dte) {
contentPane.setBorder(null);
super.dragExit(dte);
}
@Override
public void drop(DropTargetDropEvent dtde) {
contentPane.setBorder(null);
}
});
} catch (TooManyListenersException e) {
log.warn("Can not init drag and drop dropTarget", e);
}
}
private void initGui() {
setContentPane(contentPane);
setTitle(Translation.getTranslatedString("SettingsDialogBundle", "windowTitle"));
getRootPane().setDefaultButton(buttonOK);
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/balloonIcon256.png")));
initSettingsList();
loadSettingsList();
loadSettings();
updateDragAndDropNotice();
buttonApply.addActionListener(e -> onApply());
donatePaypalButton.addActionListener(e -> UrlsProceed.openUrl(StringConstants.DONATE_PAYPAL_URL));
donatePaypalButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
buttonOK.addActionListener(e -> onSave());
buttonCancel.addActionListener(e -> onCancel());
aboutButton.addActionListener(e -> onAbout());
// call onCancel() when cross is clicked
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
scrollpane.setBorder(null);
settingsSavedLabel.setVisible(false);
initDropTarget();
browserSetterPanel.init(); //don't forget it or it will crash fileBrowser
pack();
setMinimumSize(new Dimension(640, 300));
// setSize(new Dimension(400, 260));
setLocation(FrameUtils.getFrameOnCenterLocationPoint(this));
translate();
}
private void initSettingsList() {
settingsList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof SettingsPanel) {
String name = "";
if (value instanceof MainSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsMainPanelName");
} else if (value instanceof BrowserSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsBrowserPanelName");
} else if (value instanceof AppearanceSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsAppearancePanelName");
} else if (value instanceof LocaleSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsLocalePanelName");
}
return super.getListCellRendererComponent(list, name, index, isSelected, cellHasFocus);
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
});
settingsList.addListSelectionListener(e -> {
scrollPaneContent.removeAll();
scrollPaneContent.add((Component) settingsList.getSelectedValue());
scrollpane.updateUI();
});
}
private void loadSettings() {
final ListModel<SettingsPanel> model = settingsList.getModel();
for (int i = 0; i < model.getSize(); i++) {
final SettingsPanel settingsPanel = model.getElementAt(i);
settingsPanel.loadSettings();
}
settingsList.setSelectedIndex(0);
}
private void loadSettingsList() {
DefaultListModel<SettingsPanel> model = new DefaultListModel<>();
mainSetterPanel = new MainSetterPanel();
browserSetterPanel = new BrowserSetterPanel();
appearanceSetterPanel = new AppearanceSetterPanel();
localeSetterPanel = new LocaleSetterPanel();
model.addElement(mainSetterPanel);
model.addElement(browserSetterPanel);
model.addElement(appearanceSetterPanel);
model.addElement(localeSetterPanel);
settingsList.setModel(model);
if (PreferencesManager.isDarkModeEnabledNow()) {
final JColorful colorful = new JColorful(ApplicationConstants.DARK_MODE_THEME);
colorful.colorize(mainSetterPanel);
colorful.colorize(browserSetterPanel);
colorful.colorize(appearanceSetterPanel);
colorful.colorize(localeSetterPanel);
}
}
private void onAbout() {
AboutApplicationDialog dialog;
if (PreferencesManager.isDarkModeEnabledNow()) {
JColorful colorful = new JColorful(ApplicationConstants.DARK_MODE_THEME);
colorful.colorizeGlobal();
dialog = new AboutApplicationDialog();
colorful.colorize(dialog);
} else {
dialog = new AboutApplicationDialog();
}
dialog.setVisible(true);
}
private void onApply() {
saveSettings();
SwingUtilities.invokeLater(this::updateUIDarkMode);
updateDragAndDropNotice();
updateLocale();
showOnApplyMessage();
}
@Override
public void translate() {
updateDragAndDropNotice();
Translation translation = new Translation("SettingsDialogBundle");
setTitle(translation.getTranslatedString("windowTitle"));
aboutButton.setText(translation.getTranslatedString("buttonAbout"));
settingsSavedLabel.setText(translation.getTranslatedString("settingsSaved"));
buttonApply.setText(translation.getTranslatedString("buttonApply"));
buttonOK.setText(translation.getTranslatedString("buttonOk"));
buttonCancel.setText(translation.getTranslatedString("buttonCancel"));
}
private void updateLocale() {
ListModel model = settingsList.getModel();
for (int i = 0; i < model.getSize(); i++) {
Object o = model.getElementAt(i);
if (o instanceof Translatable) {
Translatable translatable = ((Translatable) o);
translatable.translate();
}
}
this.translate();
}
private void onCancel() {
dispose();
}
private void onSave() {
saveSettings();
dispose();
}
private void showOnApplyMessage() {
settingsSavedLabel.setVisible(true);
if (settingsSavedTimer == null) {
settingsSavedTimer = new Timer(5000, e -> {
settingsSavedLabel.setVisible(false);
});
settingsSavedTimer.setRepeats(false);
}
settingsSavedTimer.restart();
}
private void updateDragAndDropNotice() {
final String translatedString = Translation.getTranslatedString("SettingsDialogBundle", "dragAndDropNotice");
dragAndDropNotice.setText(translatedString.replace("{}", PreferencesManager.getConverterExportExtension()));
}
private void saveSettings() {
ListModel model = settingsList.getModel();
for (int i = 0; i < model.getSize(); i++) {
Object o = model.getElementAt(i);
if (o instanceof SettingsPanel) {
SettingsPanel panel = ((SettingsPanel) o);
panel.saveSettings();
}
}
}
private void updateUIDarkMode() {
if (PreferencesManager.isDarkModeEnabledNow()) {
try {
final JColorful colorful = new JColorful(ApplicationConstants.DARK_MODE_THEME);
colorful.colorize(this);
colorful.colorize(mainSetterPanel);
colorful.colorize(browserSetterPanel);
colorful.colorize(appearanceSetterPanel);
} catch (Exception e) {
log.warn("Could not colorize component", e);
}
}
}
}
|
src/main/java/com/github/benchdoos/weblocopener/gui/SettingsDialog.java
|
/*
* (C) Copyright 2019. Eugene Zrazhevsky and others.
* 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.
* Contributors:
* Eugene Zrazhevsky <[email protected]>
*/
package com.github.benchdoos.weblocopener.gui;
import com.github.benchdoos.jcolorful.core.JColorful;
import com.github.benchdoos.weblocopener.core.Translation;
import com.github.benchdoos.weblocopener.core.constants.ApplicationConstants;
import com.github.benchdoos.weblocopener.core.constants.StringConstants;
import com.github.benchdoos.weblocopener.gui.panels.*;
import com.github.benchdoos.weblocopener.preferences.PreferencesManager;
import com.github.benchdoos.weblocopener.service.Analyzer;
import com.github.benchdoos.weblocopener.service.UrlsProceed;
import com.github.benchdoos.weblocopener.utils.Converter;
import com.github.benchdoos.weblocopener.utils.FrameUtils;
import com.github.benchdoos.weblocopener.utils.Logging;
import com.github.benchdoos.weblocopener.utils.UserUtils;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.TooManyListenersException;
public class SettingsDialog extends JFrame implements Translatable {
private static final Logger log = LogManager.getLogger(Logging.getCurrentClassName());
private Timer settingsSavedTimer = null;
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JButton aboutButton;
private JScrollPane scrollpane;
private JList<SettingsPanel> settingsList;
private JPanel scrollPaneContent;
private JButton buttonApply;
private JLabel settingsSavedLabel;
private JButton donatePaypalButton;
private JLabel dragAndDropNotice;
private BrowserSetterPanel browserSetterPanel;
private MainSetterPanel mainSetterPanel;
private AppearanceSetterPanel appearanceSetterPanel;
private LocaleSetterPanel localeSetterPanel;
public SettingsDialog() {
$$$setupUI$$$();
log.debug("Creating settings dialog.");
initGui();
log.debug("Settings dialog created.");
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(3, 2, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(2, 5, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new GridConstraints(2, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2, new GridConstraints(1, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
this.$$$loadButtonText$$$(buttonOK, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonOk"));
panel2.add(buttonOK, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
this.$$$loadButtonText$$$(buttonCancel, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonCancel"));
panel2.add(buttonCancel, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonApply = new JButton();
this.$$$loadButtonText$$$(buttonApply, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonApply"));
panel2.add(buttonApply, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
aboutButton = new JButton();
this.$$$loadButtonText$$$(aboutButton, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("buttonAbout"));
panel1.add(aboutButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
dragAndDropNotice = new JLabel();
dragAndDropNotice.setForeground(new Color(-6316129));
this.$$$loadLabelText$$$(dragAndDropNotice, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("dragAndDropNotice"));
panel1.add(dragAndDropNotice, new GridConstraints(0, 0, 1, 5, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
settingsSavedLabel = new JLabel();
settingsSavedLabel.setForeground(new Color(-16732650));
this.$$$loadLabelText$$$(settingsSavedLabel, ResourceBundle.getBundle("translations/SettingsDialogBundle").getString("settingsSaved"));
panel1.add(settingsSavedLabel, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
donatePaypalButton = new JButton();
donatePaypalButton.setBorderPainted(false);
donatePaypalButton.setContentAreaFilled(false);
donatePaypalButton.setIcon(new ImageIcon(getClass().getResource("/images/donate16.png")));
donatePaypalButton.setIconTextGap(0);
donatePaypalButton.setMargin(new Insets(0, 0, 0, 0));
donatePaypalButton.setOpaque(false);
donatePaypalButton.setText("");
panel1.add(donatePaypalButton, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer2 = new Spacer();
contentPane.add(spacer2, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final JSplitPane splitPane1 = new JSplitPane();
contentPane.add(splitPane1, new GridConstraints(0, 0, 2, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, 200), null, 0, false));
final JScrollPane scrollPane1 = new JScrollPane();
scrollPane1.setMinimumSize(new Dimension(128, 15));
splitPane1.setLeftComponent(scrollPane1);
settingsList = new JList();
settingsList.setSelectionMode(0);
scrollPane1.setViewportView(settingsList);
scrollpane = new JScrollPane();
splitPane1.setRightComponent(scrollpane);
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));
scrollpane.setViewportView(panel3);
panel3.add(scrollPaneContent, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final Spacer spacer3 = new Spacer();
panel3.add(spacer3, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
private void $$$loadLabelText$$$(JLabel component, String text) {
StringBuffer result = new StringBuffer();
boolean haveMnemonic = false;
char mnemonic = '\0';
int mnemonicIndex = -1;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '&') {
i++;
if (i == text.length()) break;
if (!haveMnemonic && text.charAt(i) != '&') {
haveMnemonic = true;
mnemonic = text.charAt(i);
mnemonicIndex = result.length();
}
}
result.append(text.charAt(i));
}
component.setText(result.toString());
if (haveMnemonic) {
component.setDisplayedMnemonic(mnemonic);
component.setDisplayedMnemonicIndex(mnemonicIndex);
}
}
/**
* @noinspection ALL
*/
private void $$$loadButtonText$$$(AbstractButton component, String text) {
StringBuffer result = new StringBuffer();
boolean haveMnemonic = false;
char mnemonic = '\0';
int mnemonicIndex = -1;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '&') {
i++;
if (i == text.length()) break;
if (!haveMnemonic && text.charAt(i) != '&') {
haveMnemonic = true;
mnemonic = text.charAt(i);
mnemonicIndex = result.length();
}
}
result.append(text.charAt(i));
}
component.setText(result.toString());
if (haveMnemonic) {
component.setMnemonic(mnemonic);
component.setDisplayedMnemonicIndex(mnemonicIndex);
}
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
private void createUIComponents() {
scrollPaneContent = new JPanel();
scrollPaneContent.setLayout(new GridLayout());
}
private void initDropTarget() {
final ImageIcon rickAndMortyIcon = new ImageIcon(Toolkit.getDefaultToolkit()
.getImage(getClass().getResource("/images/easter/rickAndMorty.gif")));
final DropTarget dropTarget = new DropTarget() {
@Override
public synchronized void drop(DropTargetDropEvent evt) {
onDrop(evt);
}
private void onDrop(DropTargetDropEvent evt) {
Translation translation = new Translation("SettingsDialogBundle");
try {
contentPane.setBorder(null);
evt.acceptDrop(DnDConstants.ACTION_COPY);
final Object transferData = evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
List<?> list = (List<?>) transferData;
ArrayList<File> files = new ArrayList<>(list.size());
int easterCounter = 0;
for (Object o : list) {
if (o instanceof File) {
File file = (File) o;
try {
if (FilenameUtils.removeExtension(file.getName()).toLowerCase().contains("rick and morty")) {
if (easterCounter == 0) {
showRickAndMortyEaster();
easterCounter++;
}
}
} catch (Exception e) {
log.warn("Rick and Morty easter egg is broken", e);
}
final String fileExtension = Analyzer.getFileExtension(file);
if (fileExtension.equalsIgnoreCase(ApplicationConstants.URL_FILE_EXTENSION)
|| fileExtension.equalsIgnoreCase(ApplicationConstants.DESKTOP_FILE_EXTENSION)) {
try {
files.add(Converter.convert(file, ApplicationConstants.WEBLOC_FILE_EXTENSION));
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
log.warn("Could not delete file: {}", file, e);
}
} catch (IOException e) {
log.warn("Could not convert *.{} to *.webloc file: {}", fileExtension, file, e);
}
} else if (fileExtension.equalsIgnoreCase(ApplicationConstants.WEBLOC_FILE_EXTENSION)) {
try {
files.add(Converter.convert(file, PreferencesManager.getConverterExportExtension()));
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
log.warn("Could not delete file: {}", file, e);
}
} catch (IOException e) {
log.warn("Could not convert *.webloc to *.{} file: {}", PreferencesManager.getConverterExportExtension(), file, e);
}
}
}
}
if (files.size() == list.size()) {
UserUtils.showTrayMessage(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME,
translation.getTranslatedString("allFilesSuccessfullyConverted")
+ files.size() + "/" + list.size(), TrayIcon.MessageType.INFO);
} else {
UserUtils.showTrayMessage(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME,
translation.getTranslatedString("someFilesFailedToConvert")
+ files.size() + "/" + list.size(), TrayIcon.MessageType.WARNING);
}
} catch (Exception ex) {
log.warn("Can not open files from drop", ex);
UserUtils.showTrayMessage(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME,
translation.getTranslatedString("couldNotConvertFiles"),
TrayIcon.MessageType.ERROR);
}
}
private void showRickAndMortyEaster() {
log.info("Look! This user has found an easter egg (Rick and Morty). Good job!");
JFrame frame = new JFrame(ApplicationConstants.WEBLOCOPENER_APPLICATION_NAME);
frame.setLayout(new GridLayout());
JLabel label = new JLabel();
label.setIcon(rickAndMortyIcon);
frame.add(label);
frame.setUndecorated(true);
frame.setSize(500, 281);
frame.setResizable(false);
frame.setLocation(FrameUtils.getFrameOnCenterLocationPoint(frame));
Timer timer = new Timer(5000, e -> frame.dispose());
timer.setRepeats(false);
timer.start();
frame.setVisible(true);
}
};
contentPane.setDropTarget(dropTarget);
try {
dropTarget.addDropTargetListener(new DropTargetAdapter() {
@Override
public void dragEnter(DropTargetDragEvent dtde) {
contentPane.setBorder(BorderFactory.createLineBorder(Color.RED));
super.dragEnter(dtde);
}
@Override
public void dragExit(DropTargetEvent dte) {
contentPane.setBorder(null);
super.dragExit(dte);
}
@Override
public void drop(DropTargetDropEvent dtde) {
contentPane.setBorder(null);
}
});
} catch (TooManyListenersException e) {
log.warn("Can not init drag and drop dropTarget", e);
}
}
private void initGui() {
setContentPane(contentPane);
setTitle(Translation.getTranslatedString("SettingsDialogBundle", "windowTitle"));
getRootPane().setDefaultButton(buttonOK);
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/balloonIcon256.png")));
initSettingsList();
loadSettingsList();
loadSettings();
updateDragAndDropNotice();
buttonApply.addActionListener(e -> onApply());
donatePaypalButton.addActionListener(e -> UrlsProceed.openUrl(StringConstants.DONATE_PAYPAL_URL));
donatePaypalButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
buttonOK.addActionListener(e -> onSave());
buttonCancel.addActionListener(e -> onCancel());
aboutButton.addActionListener(e -> onAbout());
// call onCancel() when cross is clicked
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
scrollpane.setBorder(null);
settingsSavedLabel.setVisible(false);
initDropTarget();
browserSetterPanel.init(); //don't forget it or it will crash fileBrowser
pack();
setMinimumSize(new Dimension(640, 300));
// setSize(new Dimension(400, 260));
setLocation(FrameUtils.getFrameOnCenterLocationPoint(this));
translate();
}
private void initSettingsList() {
settingsList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof SettingsPanel) {
String name = "";
if (value instanceof MainSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsMainPanelName");
} else if (value instanceof BrowserSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsBrowserPanelName");
} else if (value instanceof AppearanceSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsAppearancePanelName");
} else if (value instanceof LocaleSetterPanel) {
name = Translation.getTranslatedString("SettingsDialogBundle", "settingsLocalePanelName");
}
return super.getListCellRendererComponent(list, name, index, isSelected, cellHasFocus);
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
});
settingsList.addListSelectionListener(e -> {
scrollPaneContent.removeAll();
scrollPaneContent.add((Component) settingsList.getSelectedValue());
scrollpane.updateUI();
});
}
private void loadSettings() {
final ListModel<SettingsPanel> model = settingsList.getModel();
for (int i = 0; i < model.getSize(); i++) {
final SettingsPanel settingsPanel = model.getElementAt(i);
settingsPanel.loadSettings();
}
settingsList.setSelectedIndex(0);
}
private void loadSettingsList() {
DefaultListModel<SettingsPanel> model = new DefaultListModel<>();
mainSetterPanel = new MainSetterPanel();
browserSetterPanel = new BrowserSetterPanel();
appearanceSetterPanel = new AppearanceSetterPanel();
localeSetterPanel = new LocaleSetterPanel();
model.addElement(mainSetterPanel);
model.addElement(browserSetterPanel);
model.addElement(appearanceSetterPanel);
model.addElement(localeSetterPanel);
settingsList.setModel(model);
if (PreferencesManager.isDarkModeEnabledNow()) {
final JColorful colorful = new JColorful(ApplicationConstants.DARK_MODE_THEME);
colorful.colorize(mainSetterPanel);
colorful.colorize(browserSetterPanel);
colorful.colorize(appearanceSetterPanel);
colorful.colorize(localeSetterPanel);
}
}
private void onAbout() {
AboutApplicationDialog dialog;
if (PreferencesManager.isDarkModeEnabledNow()) {
JColorful colorful = new JColorful(ApplicationConstants.DARK_MODE_THEME);
colorful.colorizeGlobal();
dialog = new AboutApplicationDialog();
colorful.colorize(dialog);
} else {
dialog = new AboutApplicationDialog();
}
dialog.setVisible(true);
}
private void onApply() {
saveSettings();
SwingUtilities.invokeLater(this::updateUIDarkMode);
updateDragAndDropNotice();
updateLocale();
showOnApplyMessage();
}
@Override
public void translate() {
updateDragAndDropNotice();
Translation translation = new Translation("SettingsDialogBundle");
aboutButton.setText(translation.getTranslatedString("buttonAbout"));
settingsSavedLabel.setText(translation.getTranslatedString("settingsSaved"));
buttonApply.setText(translation.getTranslatedString("buttonApply"));
buttonOK.setText(translation.getTranslatedString("buttonOk"));
buttonCancel.setText(translation.getTranslatedString("buttonCancel"));
}
private void updateLocale() {
ListModel model = settingsList.getModel();
for (int i = 0; i < model.getSize(); i++) {
Object o = model.getElementAt(i);
if (o instanceof Translatable) {
Translatable translatable = ((Translatable) o);
translatable.translate();
}
}
this.translate();
}
private void onCancel() {
dispose();
}
private void onSave() {
saveSettings();
dispose();
}
private void showOnApplyMessage() {
settingsSavedLabel.setVisible(true);
if (settingsSavedTimer == null) {
settingsSavedTimer = new Timer(5000, e -> {
settingsSavedLabel.setVisible(false);
});
settingsSavedTimer.setRepeats(false);
}
settingsSavedTimer.restart();
}
private void updateDragAndDropNotice() {
final String translatedString = Translation.getTranslatedString("SettingsDialogBundle", "dragAndDropNotice");
dragAndDropNotice.setText(translatedString.replace("{}", PreferencesManager.getConverterExportExtension()));
}
private void saveSettings() {
ListModel model = settingsList.getModel();
for (int i = 0; i < model.getSize(); i++) {
Object o = model.getElementAt(i);
if (o instanceof SettingsPanel) {
SettingsPanel panel = ((SettingsPanel) o);
panel.saveSettings();
}
}
}
private void updateUIDarkMode() {
if (PreferencesManager.isDarkModeEnabledNow()) {
try {
final JColorful colorful = new JColorful(ApplicationConstants.DARK_MODE_THEME);
colorful.colorize(this);
colorful.colorize(mainSetterPanel);
colorful.colorize(browserSetterPanel);
colorful.colorize(appearanceSetterPanel);
} catch (Exception e) {
log.warn("Could not colorize component", e);
}
}
}
}
|
Fixed title on apply update
|
src/main/java/com/github/benchdoos/weblocopener/gui/SettingsDialog.java
|
Fixed title on apply update
|
<ide><path>rc/main/java/com/github/benchdoos/weblocopener/gui/SettingsDialog.java
<ide> public void translate() {
<ide> updateDragAndDropNotice();
<ide> Translation translation = new Translation("SettingsDialogBundle");
<add> setTitle(translation.getTranslatedString("windowTitle"));
<ide> aboutButton.setText(translation.getTranslatedString("buttonAbout"));
<ide> settingsSavedLabel.setText(translation.getTranslatedString("settingsSaved"));
<ide> buttonApply.setText(translation.getTranslatedString("buttonApply"));
|
|
Java
|
apache-2.0
|
4140e40f03076196944360c356785c748037e079
| 0 |
thomaskrause/ANNIS,zangsir/ANNIS,thomaskrause/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,zangsir/ANNIS,thomaskrause/ANNIS,korpling/ANNIS,thomaskrause/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS,thomaskrause/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,zangsir/ANNIS
|
/*
* Copyright 2009-2011 Collaborative Research Centre SFB 632
*
* 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 annis.gui.visualizers.iframe.dependency;
import annis.gui.MatchedNodeColors;
import annis.gui.visualizers.VisualizerInput;
import annis.gui.visualizers.iframe.WriterVisualizer;
import static annis.model.AnnisConstants.*;
import de.hu_berlin.german.korpling.saltnpepper.salt.graph.Edge;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDataSourceSequence;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDocumentGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SPointingRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STYPE_NAME;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SAnnotation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SFeature;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SNode;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SRelation;
import java.io.IOException;
import java.io.Writer;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
/**
*
* @author Thomas Krause <[email protected]>
* @author Benjamin Weißenfels<[email protected]>
* @author Kim Gerdes
*/
@PluginImplementation
public class VakyarthaDependencyTree extends WriterVisualizer
{
private static final org.slf4j.Logger log = LoggerFactory.
getLogger(VakyarthaDependencyTree.class);
private Writer theWriter;
private VisualizerInput input;
private final String NODE_ANNOTATION_NAME = "np_form";
@Override
public String getShortName()
{
return "arch_dependency";
}
@Override
public void writeOutput(VisualizerInput input, Writer writer)
{
theWriter = writer;
this.input = input;
printHTMLOutput();
}
public void printHTMLOutput()
{
SDocumentGraph sDocumentGraph = input.getSResult().getSDocumentGraph();
/**
* Try to create a sorted map of nodes. The left annis feature token index
* is used for sorting the nodes. It is possible the different nodes has the
* same left token index, but the probability of this is small and it seem's
* not to make much sense to visualize this. Mabye we should use the node
* id.
*/
Map<SNode, Integer> selectedNodes = new TreeMap<SNode, Integer>(new Comparator<SNode>()
{
private int getIdx(SNode snode)
{
if (snode instanceof SToken)
{
SFeature sF = snode.getSFeature(ANNIS_NS, FEAT_TOKENINDEX);
return sF != null ? (int) (long) sF.getSValueSNUMERIC() : -1;
}
else
{
SFeature sF = snode.getSFeature(ANNIS_NS, FEAT_LEFTTOKEN);
return sF != null ? (int) (long) sF.getSValueSNUMERIC() : -1;
}
}
@Override
public int compare(SNode o1, SNode o2)
{
int tok1 = getIdx(o1);
int tok2 = getIdx(o2);
if (tok1 < tok2)
{
return -1;
}
if (tok1 == tok2)
{
return 0;
}
else
{
return 1;
}
}
});
for (SNode n : sDocumentGraph.getSNodes())
{
if (hasAnno(n))
{
SFeature sFeature = n.getSFeature(ANNIS_NS, FEAT_TOKENINDEX);
int tokenIdx = sFeature != null ? (int) (long) sFeature.
getSValueSNUMERIC() : -1;
selectedNodes.put(n, tokenIdx);
}
}
Map<SNode, Integer> node2Int = new HashMap<SNode, Integer>();
int count = 0;
for (SNode tok : selectedNodes.keySet())
{
node2Int.put(tok, count++);
}
try
{
println("<html>");
println("<head>");
println(
"<script type=\"text/javascript\" src=\""
+ input.getResourcePath("vakyartha/jquery-1.4.2.min.js") + "\"></script>");
println("<script type=\"text/javascript\" src=\""
+ input.getResourcePath("vakyartha/raphael.js") + "\"></script>");
println(
"<script type=\"text/javascript\" src=\""
+ input.getResourcePath("vakyartha/vakyarthaDependency.js") + "\"></script>");
// output the data for the javascript
println("<script type=\"text/javascript\">");
println("fcolors={};");
println("shownfeatures=[\"t\"];");
println("tokens=new Object();");
count = 0;
for (SNode tok : selectedNodes.keySet())
{
JSONObject o = new JSONObject();
o.put("t", getText(tok));
JSONObject govs = new JSONObject();
EList<Edge> sEdges = tok.getSGraph().getInEdges(tok.getSId());
for (Edge e : sEdges)
{
if (!(e instanceof SPointingRelation) || !(e.getSource() instanceof SNode))
{
continue;
}
SPointingRelation sRelation = (SPointingRelation) e;
SNode source = (SNode) sRelation.getSource();
String label = "";
for (SAnnotation anno : sRelation.getSAnnotations())
{
label = anno.getSValueSTEXT();
break;
}
if (sRelation.getSource() == null
|| !node2Int.containsKey(source))
{
govs.put("root", label);
}
else
{
govs.put(String.valueOf(node2Int.get(source)), label);
}
}
o.put("govs", govs);
JSONObject attris = new JSONObject();
JSONObject tAttris = new JSONObject();
String tokenColor = "black";
if (input.getMarkedAndCovered().containsKey(tok))
{
int colorNumber = ((int) (long) input.getMarkedAndCovered().get(tok)) - 1;
tokenColor = MatchedNodeColors.values()[colorNumber].getHTMLColor();
}
tAttris.put("fill", tokenColor);
tAttris.put("font", "11px Arial,Tahoma,Helvetica,Sans-Serif");
attris.put("t", tAttris);
o.put("attris", attris);
theWriter.append("tokens[").append("" + count++).append("]=");
theWriter.append(o.toString().replaceAll("\n", " "));
theWriter.append(";\n");
}
println("</script>");
println("</head>");
println("<body>");
// the div to render the javascript to
println(
"<div id=\"holder\" style=\"background:white; position:relative;\"> </div>");
println("</body>");
println("</html>");
}
catch (JSONException ex)
{
log.error(null, ex);
}
catch (IOException ex)
{
log.error(null, ex);
}
}
private void println(String s) throws IOException
{
println(s, 0);
}
private void println(String s, int indent) throws IOException
{
for (int i = 0; i < indent; i++)
{
theWriter.append("\t");
}
theWriter.append(s);
theWriter.append("\n");
}
private String getText(SNode node)
{
SDocumentGraph sDocumentGraph = input.getSResult().getSDocumentGraph();
EList<STYPE_NAME> textRelations = new BasicEList<STYPE_NAME>();
textRelations.add(STYPE_NAME.STEXT_OVERLAPPING_RELATION);
EList<SDataSourceSequence> sequences = sDocumentGraph.
getOverlappedDSSequences(node, textRelations);
if (sequences != null && sequences.size() > 0)
{
return ((STextualDS) sequences.get(0).getSSequentialDS()).getSText().
substring(sequences.get(0).getSStart(), sequences.get(0).getSEnd());
}
return "";
}
/**
* Checks if the node carries the
* {@link VakyarthaDependencyTree#NODE_ANNOTATION_NAME}.
*/
private boolean hasAnno(SNode n)
{
EList<SAnnotation> annos = n.getSAnnotations();
for (SAnnotation a : annos)
{
if (NODE_ANNOTATION_NAME.equals(a.getName()))
{
return true;
}
}
return false;
}
}
|
annis-gui/src/main/java/annis/gui/visualizers/iframe/dependency/VakyarthaDependencyTree.java
|
/*
* Copyright 2009-2011 Collaborative Research Centre SFB 632
*
* 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 annis.gui.visualizers.iframe.dependency;
import annis.gui.MatchedNodeColors;
import annis.gui.visualizers.VisualizerInput;
import annis.gui.visualizers.iframe.WriterVisualizer;
import static annis.model.AnnisConstants.*;
import de.hu_berlin.german.korpling.saltnpepper.salt.graph.Edge;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDataSourceSequence;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDocumentGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SPointingRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STYPE_NAME;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SAnnotation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SFeature;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SNode;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SRelation;
import java.io.IOException;
import java.io.Writer;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
/**
*
* @author Thomas Krause <[email protected]>
* @author Benjamin Weißenfels<[email protected]>
* @author Kim Gerdes
*/
@PluginImplementation
public class VakyarthaDependencyTree extends WriterVisualizer
{
private static final org.slf4j.Logger log = LoggerFactory.
getLogger(VakyarthaDependencyTree.class);
private Writer theWriter;
private VisualizerInput input;
private final String NODE_ANNOTATION_NAME = "np_form";
@Override
public String getShortName()
{
return "arch_dependency";
}
@Override
public void writeOutput(VisualizerInput input, Writer writer)
{
theWriter = writer;
this.input = input;
printHTMLOutput();
}
public void printHTMLOutput()
{
SDocumentGraph sDocumentGraph = input.getSResult().getSDocumentGraph();
/**
* Try to create a sorted map of nodes. The left annis feature token index
* is used for sorting the nodes. It is possible the different nodes has the
* same left token index, but the probability of this is small and it seem's
* not to make much sense to visualize this. Mabye we should use the node
* id.
*/
Map<SNode, Integer> selectedNodes = new TreeMap<SNode, Integer>(new Comparator<SNode>()
{
private int getIdx(SNode snode)
{
if (snode instanceof SToken)
{
SFeature sF = snode.getSFeature(ANNIS_NS, FEAT_TOKENINDEX);
return sF != null ? (int) (long) sF.getSValueSNUMERIC() : -1;
}
else
{
SFeature sF = snode.getSFeature(ANNIS_NS, FEAT_LEFTTOKEN);
return sF != null ? (int) (long) sF.getSValueSNUMERIC() : -1;
}
}
@Override
public int compare(SNode o1, SNode o2)
{
int tok1 = getIdx(o1);
int tok2 = getIdx(o2);
if (tok1 < tok2)
{
return -1;
}
if (tok1 == tok2)
{
return 0;
}
else
{
return 1;
}
}
});
for (SNode n : sDocumentGraph.getSNodes())
{
if (hasAnno(n))
{
SFeature sFeature = n.getSFeature(ANNIS_NS, FEAT_TOKENINDEX);
int tokenIdx = sFeature != null ? (int) (long) sFeature.
getSValueSNUMERIC() : -1;
selectedNodes.put(n, tokenIdx);
}
}
Map<SNode, Integer> tok2Int = new HashMap<SNode, Integer>();
int count = 0;
for (SNode tok : selectedNodes.keySet())
{
tok2Int.put(tok, count++);
}
try
{
println("<html>");
println("<head>");
println(
"<script type=\"text/javascript\" src=\""
+ input.getResourcePath("vakyartha/jquery-1.4.2.min.js") + "\"></script>");
println("<script type=\"text/javascript\" src=\""
+ input.getResourcePath("vakyartha/raphael.js") + "\"></script>");
println(
"<script type=\"text/javascript\" src=\""
+ input.getResourcePath("vakyartha/vakyarthaDependency.js") + "\"></script>");
// output the data for the javascript
println("<script type=\"text/javascript\">");
println("fcolors={};");
println("shownfeatures=[\"t\"];");
println("tokens=new Object();");
count = 0;
for (SNode tok : selectedNodes.keySet())
{
JSONObject o = new JSONObject();
o.put("t", getText(tok));
JSONObject govs = new JSONObject();
EList<Edge> sEdges = tok.getSGraph().getInEdges(tok.getSId());
for (Edge e : sEdges)
{
if (!(e instanceof SPointingRelation) || !(e.getSource() instanceof SNode))
{
continue;
}
SPointingRelation sRelation = (SPointingRelation) e;
SNode source = (SNode) sRelation.getSource();
String label = "";
for (SAnnotation anno : sRelation.getSAnnotations())
{
label = anno.getSValueSTEXT();
break;
}
if (sRelation.getSource() == null
|| !tok2Int.containsKey(source))
{
govs.put("root", label);
}
else
{
govs.put(String.valueOf(tok2Int.get(source)), label);
}
}
o.put("govs", govs);
JSONObject attris = new JSONObject();
JSONObject tAttris = new JSONObject();
String tokenColor = "black";
if (input.getMarkedAndCovered().containsKey(tok))
{
int colorNumber = ((int) (long) input.getMarkedAndCovered().get(tok)) - 1;
tokenColor = MatchedNodeColors.values()[colorNumber].getHTMLColor();
}
tAttris.put("fill", tokenColor);
tAttris.put("font", "11px Arial,Tahoma,Helvetica,Sans-Serif");
attris.put("t", tAttris);
o.put("attris", attris);
theWriter.append("tokens[").append("" + count++).append("]=");
theWriter.append(o.toString().replaceAll("\n", " "));
theWriter.append(";\n");
}
println("</script>");
println("</head>");
println("<body>");
// the div to render the javascript to
println(
"<div id=\"holder\" style=\"background:white; position:relative;\"> </div>");
println("</body>");
println("</html>");
}
catch (JSONException ex)
{
log.error(null, ex);
}
catch (IOException ex)
{
log.error(null, ex);
}
}
private void println(String s) throws IOException
{
println(s, 0);
}
private void println(String s, int indent) throws IOException
{
for (int i = 0; i < indent; i++)
{
theWriter.append("\t");
}
theWriter.append(s);
theWriter.append("\n");
}
private String getText(SNode node)
{
SDocumentGraph sDocumentGraph = input.getSResult().getSDocumentGraph();
EList<STYPE_NAME> textRelations = new BasicEList<STYPE_NAME>();
textRelations.add(STYPE_NAME.STEXT_OVERLAPPING_RELATION);
EList<SDataSourceSequence> sequences = sDocumentGraph.
getOverlappedDSSequences(node, textRelations);
if (sequences != null && sequences.size() > 0)
{
return ((STextualDS) sequences.get(0).getSSequentialDS()).getSText().
substring(sequences.get(0).getSStart(), sequences.get(0).getSEnd());
}
return "";
}
/**
* Checks if the node carries the
* {@link VakyarthaDependencyTree#NODE_ANNOTATION_NAME}.
*/
private boolean hasAnno(SNode n)
{
EList<SAnnotation> annos = n.getSAnnotations();
for (SAnnotation a : annos)
{
if (NODE_ANNOTATION_NAME.equals(a.getName()))
{
return true;
}
}
return false;
}
}
|
Refactor name
|
annis-gui/src/main/java/annis/gui/visualizers/iframe/dependency/VakyarthaDependencyTree.java
|
Refactor name
|
<ide><path>nnis-gui/src/main/java/annis/gui/visualizers/iframe/dependency/VakyarthaDependencyTree.java
<ide> }
<ide> }
<ide>
<del> Map<SNode, Integer> tok2Int = new HashMap<SNode, Integer>();
<add> Map<SNode, Integer> node2Int = new HashMap<SNode, Integer>();
<ide> int count = 0;
<ide> for (SNode tok : selectedNodes.keySet())
<ide> {
<del> tok2Int.put(tok, count++);
<add> node2Int.put(tok, count++);
<ide> }
<ide>
<ide> try
<ide> }
<ide>
<ide> if (sRelation.getSource() == null
<del> || !tok2Int.containsKey(source))
<add> || !node2Int.containsKey(source))
<ide> {
<ide> govs.put("root", label);
<ide> }
<ide> else
<ide> {
<del> govs.put(String.valueOf(tok2Int.get(source)), label);
<add> govs.put(String.valueOf(node2Int.get(source)), label);
<ide> }
<ide>
<ide> }
|
|
Java
|
apache-2.0
|
deca80c97839f30bd2d29e3482301f1a9fa1a557
| 0 |
bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto
|
package com.facebook.presto;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.RecordCursor;
import com.facebook.presto.spi.RecordSet;
import com.facebook.presto.spi.TableMetadata;
import com.facebook.presto.tpch.TpchMetadata;
import com.facebook.presto.tuple.Tuple;
import com.facebook.presto.tuple.TupleInfo;
import com.facebook.presto.util.MaterializedResult;
import com.facebook.presto.util.MaterializedTuple;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimaps;
import io.airlift.log.Logger;
import io.airlift.log.Logging;
import io.airlift.slice.Slices;
import io.airlift.units.Duration;
import org.intellij.lang.annotations.Language;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.PreparedBatch;
import org.skife.jdbi.v2.PreparedBatchPart;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_LINEITEM_METADATA;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_LINEITEM_NAME;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_ORDERS_METADATA;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_ORDERS_NAME;
import static com.facebook.presto.tuple.TupleInfo.Type.DOUBLE;
import static com.facebook.presto.tuple.TupleInfo.Type.FIXED_INT_64;
import static com.facebook.presto.tuple.TupleInfo.Type.VARIABLE_BINARY;
import static com.facebook.presto.util.InMemoryTpchBlocksProvider.readTpchRecords;
import static com.facebook.presto.util.MaterializedResult.resultBuilder;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.transform;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
public abstract class AbstractTestQueries
{
private Handle handle;
@Test
public void testComplexQuery()
throws Exception
{
MaterializedResult actual = computeActual("SELECT sum(orderkey), row_number() OVER (ORDER BY orderkey)\n" +
"FROM orders\n" +
"WHERE orderkey <= 10\n" +
"GROUP BY orderkey\n" +
"HAVING sum(orderkey) >= 3\n" +
"ORDER BY orderkey DESC\n" +
"LIMIT 3");
MaterializedResult expected = resultBuilder(FIXED_INT_64, FIXED_INT_64)
.row(7, 5)
.row(6, 4)
.row(5, 3)
.build();
assertEquals(actual, expected);
}
@Test
public void testSumOfNulls()
throws Exception
{
assertQuery("SELECT orderstatus, sum(CAST(NULL AS BIGINT)) FROM orders GROUP BY orderstatus");
}
@Test
public void testApproximateCountDistinct()
throws Exception
{
MaterializedResult actual = computeActual("SELECT approx_distinct(custkey) FROM orders");
MaterializedResult expected = resultBuilder(FIXED_INT_64)
.row(971)
.build();
assertEqualsIgnoreOrder(actual.getMaterializedTuples(), expected.getMaterializedTuples());
}
@Test
public void testApproximateCountDistinctGroupBy()
throws Exception
{
MaterializedResult actual = computeActual("SELECT orderstatus, approx_distinct(custkey) FROM orders GROUP BY orderstatus");
MaterializedResult expected = resultBuilder(actual.getTupleInfo())
.row("O", 969)
.row("F", 964)
.row("P", 301)
.build();
assertEqualsIgnoreOrder(actual.getMaterializedTuples(), expected.getMaterializedTuples());
}
@Test
public void testJoinWithMultiFieldGroupBy()
throws Exception
{
assertQuery("SELECT orderstatus FROM lineitem JOIN (SELECT DISTINCT orderkey, orderstatus FROM ORDERS) T on lineitem.orderkey = T.orderkey");
}
@Test
public void testGroupByMultipleFieldsWithPredicateOnAggregationArgument()
throws Exception
{
assertQuery("SELECT custkey, orderstatus, MAX(orderkey) FROM ORDERS WHERE orderkey = 1 GROUP BY custkey, orderstatus");
}
@Test
public void testReorderOutputsOfGroupByAggregation()
throws Exception
{
assertQuery(
"SELECT orderstatus, a, custkey, b FROM (SELECT custkey, orderstatus, -COUNT(*) a, MAX(orderkey) b FROM ORDERS WHERE orderkey = 1 GROUP BY custkey, orderstatus) T");
}
@Test
public void testGroupAggregationOverNestedGroupByAggregation()
throws Exception
{
assertQuery("SELECT sum(custkey), max(orderstatus), min(c) FROM (SELECT orderstatus, custkey, COUNT(*) c FROM ORDERS GROUP BY orderstatus, custkey) T");
}
@Test
public void testDistinctMultipleFields()
throws Exception
{
assertQuery("SELECT DISTINCT custkey, orderstatus FROM ORDERS");
}
@Test
public void testArithmeticNegation()
throws Exception
{
assertQuery("SELECT -custkey FROM orders");
}
@Test
public void testDistinct()
throws Exception
{
assertQuery("SELECT DISTINCT custkey FROM orders");
}
// TODO: we need to properly propagate exceptions with their actual classes
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = "DISTINCT in aggregation parameters not yet supported")
public void testCountDistinct()
throws Exception
{
assertQuery("SELECT COUNT(DISTINCT custkey) FROM orders");
}
@Test
public void testDistinctWithOrderBy()
throws Exception
{
assertQueryOrdered("SELECT DISTINCT custkey FROM orders ORDER BY custkey LIMIT 10");
}
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = "For SELECT DISTINCT, ORDER BY expressions must appear in select list")
public void testDistinctWithOrderByNotInSelect()
throws Exception
{
assertQueryOrdered("SELECT DISTINCT custkey FROM orders ORDER BY orderkey LIMIT 10");
}
@Test
public void testOrderByLimit()
throws Exception
{
assertQueryOrdered("SELECT custkey, orderstatus FROM ORDERS ORDER BY orderkey DESC LIMIT 10");
}
@Test
public void testOrderByExpressionWithLimit()
throws Exception
{
assertQueryOrdered("SELECT custkey, orderstatus FROM ORDERS ORDER BY orderkey + 1 DESC LIMIT 10");
}
@Test
public void testGroupByOrderByLimit()
throws Exception
{
assertQueryOrdered("SELECT custkey, SUM(totalprice) FROM ORDERS GROUP BY custkey ORDER BY SUM(totalprice) DESC LIMIT 10");
}
@Test
public void testLimitZero()
throws Exception
{
assertQuery("SELECT custkey, totalprice FROM orders LIMIT 0");
}
@Test
public void testRepeatedAggregations()
throws Exception
{
assertQuery("SELECT SUM(orderkey), SUM(orderkey) FROM ORDERS");
}
@Test
public void testRepeatedOutputs()
throws Exception
{
assertQuery("SELECT orderkey a, orderkey b FROM ORDERS WHERE orderstatus = 'F'");
}
@Test
public void testLimit()
throws Exception
{
MaterializedResult actual = computeActual("SELECT orderkey FROM ORDERS LIMIT 10");
MaterializedResult all = computeExpected("SELECT orderkey FROM ORDERS", actual.getTupleInfo());
assertEquals(actual.getMaterializedTuples().size(), 10);
assertTrue(all.getMaterializedTuples().containsAll(actual.getMaterializedTuples()));
}
@Test
public void testAggregationWithLimit()
throws Exception
{
MaterializedResult actual = computeActual("SELECT custkey, SUM(totalprice) FROM ORDERS GROUP BY custkey LIMIT 10");
MaterializedResult all = computeExpected("SELECT custkey, SUM(totalprice) FROM ORDERS GROUP BY custkey", actual.getTupleInfo());
assertEquals(actual.getMaterializedTuples().size(), 10);
assertTrue(all.getMaterializedTuples().containsAll(actual.getMaterializedTuples()));
}
@Test
public void testLimitInInlineView()
throws Exception
{
MaterializedResult actual = computeActual("SELECT orderkey FROM (SELECT orderkey FROM ORDERS LIMIT 100) T LIMIT 10");
MaterializedResult all = computeExpected("SELECT orderkey FROM ORDERS", actual.getTupleInfo());
assertEquals(actual.getMaterializedTuples().size(), 10);
assertTrue(all.getMaterializedTuples().containsAll(actual.getMaterializedTuples()));
}
@Test
public void testCountAll()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM ORDERS");
}
@Test
public void testCountColumn()
throws Exception
{
assertQuery("SELECT COUNT(orderkey) FROM ORDERS");
assertQuery("SELECT COUNT(orderstatus) FROM ORDERS");
assertQuery("SELECT COUNT(orderdate) FROM ORDERS");
assertQuery("SELECT COUNT(1) FROM ORDERS");
assertQuery("SELECT COUNT(NULLIF(orderstatus, 'F')) FROM ORDERS");
assertQuery("SELECT COUNT(CAST(NULL AS BIGINT)) FROM ORDERS"); // todo: make COUNT(null) work
}
@Test
public void testWildcard()
throws Exception
{
assertQuery("SELECT * FROM ORDERS");
}
@Test
public void testMultipleWildcards()
throws Exception
{
assertQuery("SELECT *, 123, * FROM ORDERS");
}
@Test
public void testMixedWildcards()
throws Exception
{
assertQuery("SELECT *, orders.*, orderkey FROM orders");
}
@Test
public void testQualifiedWildcardFromAlias()
throws Exception
{
assertQuery("SELECT T.* FROM ORDERS T");
}
@Test
public void testQualifiedWildcardFromInlineView()
throws Exception
{
assertQuery("SELECT T.* FROM (SELECT orderkey + custkey FROM ORDERS) T");
}
@Test
public void testQualifiedWildcard()
throws Exception
{
assertQuery("SELECT ORDERS.* FROM ORDERS");
}
@Test
public void testAverageAll()
throws Exception
{
assertQuery("SELECT AVG(totalprice) FROM ORDERS");
}
@Test
public void testVariance()
throws Exception
{
// int64
assertQuery("SELECT VAR_SAMP(custkey) FROM ORDERS");
assertQuery("SELECT VAR_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT VAR_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT VAR_SAMP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT VAR_SAMP(totalprice) FROM ORDERS");
assertQuery("SELECT VAR_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT VAR_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT VAR_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testVariancePop()
throws Exception
{
// int64
assertQuery("SELECT VAR_POP(custkey) FROM ORDERS");
assertQuery("SELECT VAR_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT VAR_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT VAR_POP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT VAR_POP(totalprice) FROM ORDERS");
assertQuery("SELECT VAR_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT VAR_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT VAR_POP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testStdDev()
throws Exception
{
// int64
assertQuery("SELECT STDDEV_SAMP(custkey) FROM ORDERS");
assertQuery("SELECT STDDEV_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT STDDEV_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT STDDEV_SAMP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM ORDERS");
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testStdDevPop()
throws Exception
{
// int64
assertQuery("SELECT STDDEV_POP(custkey) FROM ORDERS");
assertQuery("SELECT STDDEV_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT STDDEV_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT STDDEV_POP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT STDDEV_POP(totalprice) FROM ORDERS");
assertQuery("SELECT STDDEV_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT STDDEV_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT STDDEV_POP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testCountAllWithPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM ORDERS WHERE orderstatus = 'F'");
}
@Test
public void testGroupByNoAggregations()
throws Exception
{
assertQuery("SELECT custkey FROM ORDERS GROUP BY custkey");
}
@Test
public void testGroupByCount()
throws Exception
{
assertQuery(
"SELECT orderstatus, COUNT(*) FROM ORDERS GROUP BY orderstatus",
"SELECT orderstatus, CAST(COUNT(*) AS INTEGER) FROM orders GROUP BY orderstatus"
);
}
@Test
public void testGroupByMultipleFields()
throws Exception
{
assertQuery("SELECT custkey, orderstatus, COUNT(*) FROM ORDERS GROUP BY custkey, orderstatus");
}
@Test
public void testGroupByWithAlias()
throws Exception
{
assertQuery(
"SELECT orderdate x, COUNT(*) FROM orders GROUP BY orderdate",
"SELECT orderdate x, CAST(COUNT(*) AS INTEGER) FROM orders GROUP BY orderdate"
);
}
@Test
public void testGroupBySum()
throws Exception
{
assertQuery("SELECT orderstatus, SUM(totalprice) FROM ORDERS GROUP BY orderstatus");
}
@Test
public void testGroupByWithWildcard()
throws Exception
{
assertQuery("SELECT * FROM (SELECT orderkey FROM orders) t GROUP BY orderkey");
}
@Test
public void testCountAllWithComparison()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE tax < discount");
}
@Test
public void testSelectWithComparison()
throws Exception
{
assertQuery("SELECT orderkey FROM lineitem WHERE tax < discount");
}
@Test
public void testCountWithNotPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE NOT tax < discount");
}
@Test
public void testCountWithNullPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE NULL");
}
@Test
public void testCountWithIsNullPredicate()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM orders WHERE NULLIF(orderstatus, 'F') IS NULL",
"SELECT COUNT(*) FROM orders WHERE orderstatus = 'F' "
);
}
@Test
public void testCountWithIsNotNullPredicate()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM orders WHERE NULLIF(orderstatus, 'F') IS NOT NULL",
"SELECT COUNT(*) FROM orders WHERE orderstatus <> 'F' "
);
}
@Test
public void testCountWithNullIfPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM orders WHERE NULLIF(orderstatus, 'F') = orderstatus ");
}
@Test
public void testCountWithCoalescePredicate()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM orders WHERE COALESCE(NULLIF(orderstatus, 'F'), 'bar') = 'bar'",
"SELECT COUNT(*) FROM orders WHERE orderstatus = 'F'"
);
}
@Test
public void testCountWithAndPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE tax < discount AND tax > 0.01 AND discount < 0.05");
}
@Test
public void testCountWithOrPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE tax < 0.01 OR discount > 0.05");
}
@Test
public void testCountWithInlineView()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM (SELECT orderkey FROM lineitem) x");
}
@Test
public void testNestedCount()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM (SELECT orderkey, COUNT(*) FROM lineitem GROUP BY orderkey) x");
}
@Test
public void testAggregationWithProjection()
throws Exception
{
assertQuery("SELECT sum(totalprice * 2) - sum(totalprice) FROM orders");
}
@Test
public void testAggregationWithProjection2()
throws Exception
{
assertQuery("SELECT sum(totalprice * 2) + sum(totalprice * 2) FROM orders");
}
@Test
public void testInlineView()
throws Exception
{
assertQuery("SELECT orderkey, custkey FROM (SELECT orderkey, custkey FROM ORDERS) U");
}
@Test
public void testAliasedInInlineView()
throws Exception
{
assertQuery("SELECT x, y FROM (SELECT orderkey x, custkey y FROM ORDERS) U");
}
@Test
public void testGroupByWithoutAggregation()
throws Exception
{
assertQuery("SELECT orderstatus FROM orders GROUP BY orderstatus");
}
@Test
public void testHistogram()
throws Exception
{
assertQuery("SELECT lines, COUNT(*) FROM (SELECT orderkey, COUNT(*) lines FROM lineitem GROUP BY orderkey) U GROUP BY lines");
}
@Test
public void testSimpleJoin()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey");
}
@Test
public void testJoinWithAlias()
throws Exception
{
assertQuery("SELECT * FROM (lineitem JOIN orders ON lineitem.orderkey = orders.orderkey) x");
}
@Test
public void testJoinWithConstantExpression()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND 123 = 123");
}
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = ".*not supported.*")
public void testJoinOnConstantExpression()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON 123 = 123");
}
@Test
public void testJoinUsing()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM lineitem join orders using (orderkey)",
"SELECT COUNT(*) FROM lineitem join orders on lineitem.orderkey = orders.orderkey"
);
}
@Test
public void testJoinWithReversedComparison()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON orders.orderkey = lineitem.orderkey");
}
@Test
public void testJoinWithComplexExpressions()
throws Exception
{
assertQuery("SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey = CAST(orders.orderkey AS BIGINT)");
}
@Test
public void testJoinWithComplexExpressions2()
throws Exception
{
assertQuery(
"SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey = CASE WHEN orders.custkey = 1 and orders.orderstatus = 'F' THEN orders.orderkey ELSE NULL END");
}
@Test
public void testJoinWithComplexExpressions3()
throws Exception
{
assertQuery(
"SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey + 1 = orders.orderkey + 1",
"SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey "
// H2 takes a million years because it can't join efficiently on a non-indexed field/expression
);
}
@Test
public void testSelfJoin()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM orders a JOIN orders b on a.orderkey = b.orderkey");
}
@Test
public void testWildcardFromJoin()
throws Exception
{
assertQuery(
"SELECT * FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b using (orderkey)",
"SELECT * FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b on a.orderkey = b.orderkey"
);
}
@Test
public void testQualifiedWildcardFromJoin()
throws Exception
{
assertQuery(
"SELECT a.*, b.* FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b using (orderkey)",
"SELECT a.*, b.* FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b on a.orderkey = b.orderkey"
);
}
@Test
public void testJoinAggregations()
throws Exception
{
assertQuery(
"SELECT x + y FROM (" +
" SELECT orderdate, COUNT(*) x FROM orders GROUP BY orderdate) a JOIN (" +
" SELECT orderdate, COUNT(*) y FROM orders GROUP BY orderdate) b ON a.orderdate = b.orderdate");
}
@Test
public void testJoinOnMultipleFields()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND lineitem.shipdate = orders.orderdate");
}
@Test
public void testJoinUsingMultipleFields()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM lineitem JOIN (SELECT orderkey, orderdate shipdate FROM ORDERS) T USING (orderkey, shipdate)",
"SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND lineitem.shipdate = orders.orderdate"
);
}
@Test
public void testJoinWithNonJoinExpression()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.custkey = 1");
}
@Test
public void testOrderBy()
throws Exception
{
assertQueryOrdered("SELECT orderstatus FROM orders ORDER BY orderstatus");
}
@Test
public void testOrderBy2()
throws Exception
{
assertQueryOrdered("SELECT orderstatus FROM orders ORDER BY orderkey DESC");
}
@Test
public void testOrderByMultipleFields()
throws Exception
{
assertQueryOrdered("SELECT custkey, orderstatus FROM orders ORDER BY custkey DESC, orderstatus");
}
@Test
public void testOrderByAlias()
throws Exception
{
assertQueryOrdered("SELECT orderstatus x FROM orders ORDER BY x ASC");
}
@Test
public void testOrderByAliasWithSameNameAsUnselectedColumn()
throws Exception
{
assertQueryOrdered("SELECT orderstatus orderdate FROM orders ORDER BY orderdate ASC");
}
@Test
public void testOrderByOrdinal()
throws Exception
{
assertQueryOrdered("SELECT orderstatus, orderdate FROM orders ORDER BY 2, 1");
}
@Test
public void testOrderByOrdinalWithWildcard()
throws Exception
{
assertQueryOrdered("SELECT * FROM orders ORDER BY 1");
}
@Test
public void testGroupByOrdinal()
throws Exception
{
assertQuery(
"SELECT orderstatus, sum(totalprice) FROM orders GROUP BY 1",
"SELECT orderstatus, sum(totalprice) FROM orders GROUP BY orderstatus");
}
@Test
public void testGroupBySearchedCase()
throws Exception
{
assertQuery("SELECT CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END");
assertQuery(
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY 1",
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END");
}
@Test
public void testGroupBySearchedCaseNoElse()
throws Exception
{
// whole CASE in group by clause
assertQuery("SELECT CASE WHEN orderstatus = 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' END");
assertQuery(
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY 1",
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' END");
assertQuery("SELECT CASE WHEN true THEN orderstatus END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
}
@Test
public void testGroupByCase()
throws Exception
{
// whole CASE in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END");
assertQuery(
"SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY 1",
"SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END");
// operand in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// condition in group by clause
assertQuery("SELECT CASE 'O' WHEN orderstatus THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// 'then' in group by clause
assertQuery("SELECT CASE 1 WHEN 1 THEN orderstatus ELSE 'x' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// 'else' in group by clause
assertQuery("SELECT CASE 1 WHEN 1 THEN 'x' ELSE orderstatus END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
}
@Test
public void testGroupByCaseNoElse()
throws Exception
{
// whole CASE in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE orderstatus WHEN 'O' THEN 'a' END");
// operand in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// condition in group by clause
assertQuery("SELECT CASE 'O' WHEN orderstatus THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// 'then' in group by clause
assertQuery("SELECT CASE 1 WHEN 1 THEN orderstatus END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
}
@Test
public void testGroupByCast()
throws Exception
{
// whole CAST in group by expression
assertQuery("SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY CAST(orderkey AS VARCHAR)");
assertQuery(
"SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY 1",
"SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY CAST(orderkey AS VARCHAR)");
// argument in group by expression
assertQuery("SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY orderkey");
}
@Test
public void testGroupByCoalesce()
throws Exception
{
// whole COALESCE in group by
assertQuery("SELECT COALESCE(orderkey, custkey), count(*) FROM orders GROUP BY COALESCE(orderkey, custkey)");
assertQuery(
"SELECT COALESCE(orderkey, custkey), count(*) FROM orders GROUP BY 1",
"SELECT COALESCE(orderkey, custkey), count(*) FROM orders GROUP BY COALESCE(orderkey, custkey)"
);
// operands in group by
assertQuery("SELECT COALESCE(orderkey, 1), count(*) FROM orders GROUP BY orderkey");
// operands in group by
assertQuery("SELECT COALESCE(1, orderkey), count(*) FROM orders GROUP BY orderkey");
}
@Test
public void testGroupByNullIf()
throws Exception
{
// whole NULLIF in group by
assertQuery("SELECT NULLIF(orderkey, custkey), count(*) FROM orders GROUP BY NULLIF(orderkey, custkey)");
assertQuery(
"SELECT NULLIF(orderkey, custkey), count(*) FROM orders GROUP BY 1",
"SELECT NULLIF(orderkey, custkey), count(*) FROM orders GROUP BY NULLIF(orderkey, custkey)");
// first operand in group by
assertQuery("SELECT NULLIF(orderkey, 1), count(*) FROM orders GROUP BY orderkey");
// second operand in group by
assertQuery("SELECT NULLIF(1, orderkey), count(*) FROM orders GROUP BY orderkey");
}
@Test
public void testGroupByExtract()
throws Exception
{
// whole expression in group by
assertQuery("SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY EXTRACT(YEAR FROM now())");
assertQuery(
"SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY 1",
"SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY EXTRACT(YEAR FROM now())");
// argument in group by
assertQuery("SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY now()");
}
@Test
public void testGroupByBetween()
throws Exception
{
// whole expression in group by
// TODO: enable once we support booleans
// assertQuery("SELECT orderkey BETWEEN 1 AND 100 FROM orders GROUP BY orderkey BETWEEN 1 AND 100 ");
// expression in group by
assertQuery("SELECT CAST(orderkey BETWEEN 1 AND 100 AS BIGINT) FROM orders GROUP BY orderkey");
// min in group by
assertQuery("SELECT CAST(50 BETWEEN orderkey AND 100 AS BIGINT) FROM orders GROUP BY orderkey");
// max in group by
assertQuery("SELECT CAST(50 BETWEEN 1 AND orderkey AS BIGINT) FROM orders GROUP BY orderkey");
}
@Test
public void testHaving()
throws Exception
{
assertQuery("SELECT orderstatus, sum(totalprice) FROM orders GROUP BY orderstatus HAVING orderstatus = 'O'");
}
@Test
public void testHaving2()
throws Exception
{
assertQuery("SELECT custkey, sum(orderkey) FROM orders GROUP BY custkey HAVING sum(orderkey) > 400000");
}
@Test
public void testHaving3()
throws Exception
{
assertQuery("SELECT custkey, sum(totalprice) * 2 FROM orders GROUP BY custkey HAVING avg(totalprice + 5) > 10");
}
@Test
public void testColumnAliases()
throws Exception
{
assertQuery(
"SELECT x, T.y, z + 1 FROM (SELECT custkey, orderstatus, totalprice FROM orders) T (x, y, z)",
"SELECT custkey, orderstatus, totalprice + 1 FROM orders");
}
@Test
public void testSameInputToAggregates()
throws Exception
{
assertQuery("SELECT max(a), max(b) FROM (SELECT custkey a, custkey b FROM orders) x");
}
@SuppressWarnings("PointlessArithmeticExpression")
@Test
public void testWindowFunctionsExpressions()
{
MaterializedResult actual = computeActual("" +
"SELECT orderkey, orderstatus\n" +
", row_number() OVER (ORDER BY orderkey * 2) *\n" +
" row_number() OVER (ORDER BY orderkey DESC) + 100\n" +
"FROM (SELECT * FROM orders ORDER BY orderkey LIMIT 10) x\n" +
"ORDER BY orderkey LIMIT 5");
MaterializedResult expected = resultBuilder(FIXED_INT_64, VARIABLE_BINARY, FIXED_INT_64)
.row(1, "O", (1 * 10) + 100)
.row(2, "O", (2 * 9) + 100)
.row(3, "F", (3 * 8) + 100)
.row(4, "O", (4 * 7) + 100)
.row(5, "F", (5 * 6) + 100)
.build();
assertEquals(actual, expected);
}
@Test
public void testWindowFunctionsFromAggregate()
throws Exception
{
MaterializedResult actual = computeActual("" +
"SELECT * FROM (\n" +
" SELECT orderstatus, clerk, sales\n" +
" , rank() OVER (PARTITION BY x.orderstatus ORDER BY sales DESC) rnk\n" +
" FROM (\n" +
" SELECT orderstatus, clerk, sum(totalprice) sales\n" +
" FROM orders\n" +
" GROUP BY orderstatus, clerk\n" +
" ) x\n" +
") x\n" +
"WHERE rnk <= 2\n" +
"ORDER BY orderstatus, rnk");
MaterializedResult expected = resultBuilder(VARIABLE_BINARY, VARIABLE_BINARY, DOUBLE, FIXED_INT_64)
.row("F", "Clerk#000000090", 2784836.61, 1)
.row("F", "Clerk#000000084", 2674447.15, 2)
.row("O", "Clerk#000000500", 2569878.29, 1)
.row("O", "Clerk#000000050", 2500162.92, 2)
.row("P", "Clerk#000000071", 841820.99, 1)
.row("P", "Clerk#000001000", 643679.49, 2)
.build();
assertEquals(actual, expected);
}
@Test
public void testOrderByWindowFunction()
throws Exception
{
MaterializedResult actual = computeActual("" +
"SELECT orderkey, row_number() OVER (ORDER BY orderkey)\n" +
"FROM (SELECT * FROM orders ORDER BY orderkey LIMIT 10)\n" +
"ORDER BY 2 DESC\n" +
"LIMIT 5");
MaterializedResult expected = resultBuilder(FIXED_INT_64, FIXED_INT_64)
.row(34, 10)
.row(33, 9)
.row(32, 8)
.row(7, 7)
.row(6, 6)
.build();
assertEquals(actual, expected);
}
@Test
public void testScalarFunction()
throws Exception
{
assertQuery("SELECT SUBSTR('Quadratically', 5, 6) FROM orders LIMIT 1");
}
@Test
public void testCast()
throws Exception
{
assertQuery("SELECT CAST(totalprice AS BIGINT) FROM orders");
assertQuery("SELECT CAST(orderkey AS DOUBLE) FROM orders");
assertQuery("SELECT CAST(orderkey AS VARCHAR) FROM orders");
}
@Test
public void testConcatOperator()
throws Exception
{
assertQuery("SELECT '12' || '34' FROM orders LIMIT 1");
}
@Test
public void testQuotedIdentifiers()
throws Exception
{
assertQuery("SELECT \"TOTALPRICE\" \"my price\" FROM \"ORDERS\"");
}
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = ".*orderkey_1.*")
public void testInvalidColumn()
throws Exception
{
computeActual("select * from lineitem l join (select orderkey_1, custkey from orders) o on l.orderkey = o.orderkey_1");
}
@Test
public void testUnaliasedSubqueries()
throws Exception
{
assertQuery("SELECT orderkey FROM (SELECT orderkey FROM orders)");
}
@Test
public void testUnaliasedSubqueries1()
throws Exception
{
assertQuery("SELECT a FROM (SELECT orderkey a FROM orders)");
}
@Test
public void testJoinUnaliasedSubqueries()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM (SELECT * FROM lineitem) join (SELECT * FROM orders) using (orderkey)",
"SELECT COUNT(*) FROM lineitem join orders on lineitem.orderkey = orders.orderkey"
);
}
@Test
public void testWith()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT * FROM orders) " +
"SELECT * FROM a",
"SELECT * FROM orders");
}
@Test
public void testWithQualifiedPrefix()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT 123 FROM orders LIMIT 1)" +
"SELECT a.* FROM a",
"SELECT 123 FROM orders LIMIT 1");
}
@Test
public void testWithAliased()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT * FROM orders) " +
"SELECT * FROM a x",
"SELECT * FROM orders");
}
@Test
public void testReferenceToWithQueryInFromClause()
throws Exception
{
assertQuery(
"WITH a AS (SELECT * FROM orders)" +
"SELECT * FROM (" +
" SELECT * FROM a" +
")",
"SELECT * FROM orders");
}
@Test
public void testWithChaining()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT orderkey n FROM orders)\n" +
", b AS (SELECT n + 1 n FROM a)\n" +
", c AS (SELECT n + 1 n FROM b)\n" +
"SELECT n + 1 FROM c",
"SELECT orderkey + 3 FROM orders");
}
@Test
public void testWithSelfJoin()
throws Exception
{
assertQuery("" +
"WITH x AS (SELECT DISTINCT orderkey FROM orders ORDER BY orderkey LIMIT 10)\n" +
"SELECT count(*) FROM x a JOIN x b USING (orderkey)", "" +
"SELECT count(*)\n" +
"FROM (SELECT DISTINCT orderkey FROM orders ORDER BY orderkey LIMIT 10) a\n" +
"JOIN (SELECT DISTINCT orderkey FROM orders ORDER BY orderkey LIMIT 10) b ON a.orderkey = b.orderkey");
}
@Test
public void testWithNestedSubqueries()
throws Exception
{
assertQuery("" +
"WITH a AS (\n" +
" WITH aa AS (SELECT 123 x FROM orders LIMIT 1)\n" +
" SELECT x y FROM aa\n" +
"), b AS (\n" +
" WITH bb AS (\n" +
" WITH bbb AS (SELECT y FROM a)\n" +
" SELECT bbb.* FROM bbb\n" +
" )\n" +
" SELECT y z FROM bb\n" +
")\n" +
"SELECT *\n" +
"FROM (\n" +
" WITH q AS (SELECT z w FROM b)\n" +
" SELECT j.*, k.*\n" +
" FROM a j\n" +
" JOIN q k ON (j.y = k.w)\n" +
") t", "" +
"SELECT 123, 123 FROM orders LIMIT 1");
}
@Test(enabled = false)
public void testWithColumnAliasing()
throws Exception
{
assertQuery(
"WITH a (id) AS (SELECT 123 FROM orders LIMIT 1) SELECT * FROM a",
"SELECT 123 FROM orders LIMIT 1");
}
@Test
public void testWithHiding()
throws Exception
{
assertQuery(
"WITH a AS (SELECT custkey FROM orders), " +
" b AS (" +
" WITH a AS (SELECT orderkey FROM orders)" +
" SELECT * FROM a" + // should refer to inner 'a'
" )" +
"SELECT * FROM b",
"SELECT orderkey FROM orders"
);
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Recursive WITH queries are not supported")
public void testWithRecursive()
throws Exception
{
computeActual("WITH RECURSIVE a AS (SELECT 123 FROM dual) SELECT * FROM a");
}
@Test
public void testCaseNoElse()
throws Exception
{
assertQuery("SELECT orderkey, CASE orderstatus WHEN 'O' THEN 'a' END FROM orders");
}
@Test
public void testIfExpression()
throws Exception
{
assertQuery(
"SELECT sum(IF(orderstatus = 'F', totalprice, 0.0)) FROM orders",
"SELECT sum(CASE WHEN orderstatus = 'F' THEN totalprice ELSE 0.0 END) FROM orders");
assertQuery(
"SELECT sum(IF(orderstatus = 'Z', totalprice)) FROM orders",
"SELECT sum(CASE WHEN orderstatus = 'Z' THEN totalprice END) FROM orders");
assertQuery(
"SELECT sum(IF(orderstatus = 'F', NULL, totalprice)) FROM orders",
"SELECT sum(CASE WHEN orderstatus = 'F' THEN NULL ELSE totalprice END) FROM orders");
assertQuery(
"SELECT IF(orderstatus = 'Z', orderkey / 0, orderkey) FROM orders",
"SELECT CASE WHEN orderstatus = 'Z' THEN orderkey / 0 ELSE orderkey END FROM orders");
assertQuery(
"SELECT sum(IF(NULLIF(orderstatus, 'F') <> 'F', totalprice, 5.1)) FROM orders",
"SELECT sum(CASE WHEN NULLIF(orderstatus, 'F') <> 'F' THEN totalprice ELSE 5.1 END) FROM orders");
}
@Test
public void testIn()
throws Exception
{
assertQuery("SELECT orderkey FROM orders WHERE orderkey IN (1, 2, 3)");
assertQuery("SELECT orderkey FROM orders WHERE orderkey IN (1.5, 2.3)");
assertQuery("SELECT orderkey FROM orders WHERE totalprice IN (1, 2, 3)");
}
@Test
public void testGroupByIf()
throws Exception
{
assertQuery(
"SELECT IF(orderkey between 1 and 5, 'orders', 'others'), sum(totalprice) FROM orders GROUP BY 1",
"SELECT CASE WHEN orderkey BETWEEN 1 AND 5 THEN 'orders' ELSE 'others' END, sum(totalprice)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderkey BETWEEN 1 AND 5 THEN 'orders' ELSE 'others' END");
}
@Test
public void testDuplicateFields()
throws Exception
{
assertQuery(
"SELECT * FROM (SELECT orderkey, orderkey FROM orders)",
"SELECT orderkey, orderkey FROM orders");
}
@Test
public void testWildcardFromSubquery()
throws Exception
{
assertQuery("SELECT * FROM (SELECT orderkey X FROM orders)");
}
@Test
public void testCaseInsensitiveOutputAliasInOrderBy()
throws Exception
{
assertQueryOrdered("SELECT orderkey X FROM orders ORDER BY x");
}
@Test
public void testCaseInsensitiveAttribute()
throws Exception
{
assertQuery("SELECT x FROM (SELECT orderkey X FROM orders)");
}
@Test
public void testCaseInsensitiveAliasedRelation()
throws Exception
{
assertQuery("SELECT A.* FROM orders a");
}
@Test
public void testSubqueryBody()
throws Exception
{
assertQuery("(SELECT orderkey, custkey FROM ORDERS)");
}
@Test
public void testSubqueryBodyOrderLimit()
throws Exception
{
assertQueryOrdered("(SELECT orderkey AS a, custkey AS b FROM ORDERS) ORDER BY a LIMIT 1");
}
@Test
public void testSubqueryBodyProjectedOrderby()
throws Exception
{
assertQueryOrdered("(SELECT orderkey, custkey FROM ORDERS) ORDER BY orderkey * -1");
}
@Test
public void testSubqueryBodyDoubleOrderby()
throws Exception
{
assertQueryOrdered("(SELECT orderkey, custkey FROM ORDERS ORDER BY custkey) ORDER BY orderkey");
}
@Test
public void testNodeRoster()
throws Exception
{
List<MaterializedTuple> result = computeActual("SELECT * FROM sys.node").getMaterializedTuples();
assertEquals(result.size(), getNodeCount());
}
@Test
public void testDual()
throws Exception
{
MaterializedResult result = computeActual("SELECT * FROM dual");
List<MaterializedTuple> tuples = result.getMaterializedTuples();
assertEquals(tuples.size(), 1);
}
@Test
public void testShowTables()
throws Exception
{
MaterializedResult result = computeActual("SHOW TABLES");
ImmutableSet<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME, TPCH_LINEITEM_NAME));
}
@Test
public void testShowTablesFrom()
throws Exception
{
MaterializedResult result = computeActual("SHOW TABLES FROM DEFAULT");
ImmutableSet<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME, TPCH_LINEITEM_NAME));
result = computeActual("SHOW TABLES FROM TPCH.DEFAULT");
tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME, TPCH_LINEITEM_NAME));
result = computeActual("SHOW TABLES FROM UNKNOWN");
tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of());
}
@Test
public void testShowTablesLike()
throws Exception
{
MaterializedResult result = computeActual("SHOW TABLES LIKE 'or%'");
ImmutableSet<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME));
}
@Test
public void testShowColumns()
throws Exception
{
MaterializedResult result = computeActual("SHOW COLUMNS FROM orders");
ImmutableSet<String> columnNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), new Function<MaterializedTuple, String>()
{
@Override
public String apply(MaterializedTuple input)
{
assertEquals(input.getFieldCount(), 4);
return (String) input.getField(0);
}
}));
assertEquals(columnNames, ImmutableSet.of("orderkey", "custkey", "orderstatus", "totalprice", "orderdate", "orderpriority", "clerk", "shippriority", "comment"));
}
@Test
public void testShowFunctions()
throws Exception
{
MaterializedResult result = computeActual("SHOW FUNCTIONS");
ImmutableMultimap<String, MaterializedTuple> functions = Multimaps.index(result.getMaterializedTuples(), new Function<MaterializedTuple, String>()
{
@Override
public String apply(MaterializedTuple input)
{
assertEquals(input.getFieldCount(), 4);
return (String) input.getField(0);
}
});
assertTrue(functions.containsKey("avg"), "Expected function names " + functions + " to contain 'avg'");
assertEquals(functions.get("avg").asList().get(0).getField(3), "aggregate");
assertTrue(functions.containsKey("abs"), "Expected function names " + functions + " to contain 'abs'");
assertEquals(functions.get("abs").asList().get(0).getField(3), "scalar");
assertTrue(functions.containsKey("rand"), "Expected function names " + functions + " to contain 'rand'");
assertEquals(functions.get("rand").asList().get(0).getField(3), "scalar (non-deterministic)");
assertTrue(functions.containsKey("rank"), "Expected function names " + functions + " to contain 'rank'");
assertEquals(functions.get("rank").asList().get(0).getField(3), "window");
}
@Test
public void testNoFrom()
throws Exception
{
assertQuery("SELECT 1 + 2, 3 + 4", "SELECT 1 + 2, 3 + 4 FROM orders LIMIT 1");
}
@Test
public void testTopNByMultipleFields()
throws Exception
{
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey ASC LIMIT 10");
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey DESC LIMIT 10");
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey ASC LIMIT 10");
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey DESC LIMIT 10");
// now try with order by fields swapped
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey ASC LIMIT 10");
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey DESC LIMIT 10");
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey ASC LIMIT 10");
assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey DESC LIMIT 10");
}
@Test
public void testUnion()
throws Exception
{
assertQuery("SELECT orderkey FROM orders UNION SELECT custkey FROM orders");
}
@Test
public void testUnionDistinct()
throws Exception
{
assertQuery("SELECT orderkey FROM orders UNION DISTINCT SELECT custkey FROM orders");
}
@Test
public void testUnionAll()
throws Exception
{
assertQuery("SELECT orderkey FROM orders UNION ALL SELECT custkey FROM orders");
}
@Test
public void testChainedUnionsWithOrder()
throws Exception
{
assertQueryOrdered("SELECT orderkey FROM orders UNION (SELECT custkey FROM orders UNION SELECT linenumber FROM lineitem) UNION ALL SELECT orderkey FROM lineitem ORDER BY orderkey");
}
@Test
public void testSubqueryUnion()
throws Exception
{
assertQueryOrdered("SELECT * FROM (SELECT orderkey FROM orders UNION SELECT custkey FROM orders UNION SELECT orderkey FROM orders) ORDER BY orderkey LIMIT 1000");
}
@BeforeClass(alwaysRun = true)
public void setupDatabase()
throws Exception
{
Logging.initialize();
handle = DBI.open("jdbc:h2:mem:test" + System.nanoTime());
RecordSet ordersRecords = readTpchRecords(TPCH_ORDERS_METADATA);
handle.execute("CREATE TABLE orders (\n" +
" orderkey BIGINT PRIMARY KEY,\n" +
" custkey BIGINT NOT NULL,\n" +
" orderstatus CHAR(1) NOT NULL,\n" +
" totalprice DOUBLE NOT NULL,\n" +
" orderdate CHAR(10) NOT NULL,\n" +
" orderpriority CHAR(15) NOT NULL,\n" +
" clerk CHAR(15) NOT NULL,\n" +
" shippriority BIGINT NOT NULL,\n" +
" comment VARCHAR(79) NOT NULL\n" +
")");
insertRows(TPCH_ORDERS_METADATA, handle, ordersRecords);
RecordSet lineItemRecords = readTpchRecords(TPCH_LINEITEM_METADATA);
handle.execute("CREATE TABLE lineitem (\n" +
" orderkey BIGINT,\n" +
" partkey BIGINT NOT NULL,\n" +
" suppkey BIGINT NOT NULL,\n" +
" linenumber BIGINT,\n" +
" quantity BIGINT NOT NULL,\n" +
" extendedprice DOUBLE NOT NULL,\n" +
" discount DOUBLE NOT NULL,\n" +
" tax DOUBLE NOT NULL,\n" +
" returnflag CHAR(1) NOT NULL,\n" +
" linestatus CHAR(1) NOT NULL,\n" +
" shipdate CHAR(10) NOT NULL,\n" +
" commitdate CHAR(10) NOT NULL,\n" +
" receiptdate CHAR(10) NOT NULL,\n" +
" shipinstruct VARCHAR(25) NOT NULL,\n" +
" shipmode VARCHAR(10) NOT NULL,\n" +
" comment VARCHAR(44) NOT NULL,\n" +
" PRIMARY KEY (orderkey, linenumber)" +
")");
insertRows(TPCH_LINEITEM_METADATA, handle, lineItemRecords);
setUpQueryFramework(TpchMetadata.TPCH_CATALOG_NAME, TpchMetadata.TPCH_SCHEMA_NAME);
}
@AfterClass(alwaysRun = true)
public void cleanupDatabase()
throws Exception
{
tearDownQueryFramework();
handle.close();
}
protected abstract int getNodeCount();
protected abstract void setUpQueryFramework(String catalog, String schema)
throws Exception;
protected void tearDownQueryFramework()
throws Exception
{
}
protected abstract MaterializedResult computeActual(@Language("SQL") String sql);
protected void assertQuery(@Language("SQL") String sql)
throws Exception
{
assertQuery(sql, sql, false);
}
private void assertQueryOrdered(@Language("SQL") String sql)
throws Exception
{
assertQuery(sql, sql, true);
}
protected void assertQuery(@Language("SQL") String actual, @Language("SQL") String expected)
throws Exception
{
assertQuery(actual, expected, false);
}
private static final Logger log = Logger.get(AbstractTestQueries.class);
private void assertQuery(@Language("SQL") String actual, @Language("SQL") String expected, boolean ensureOrdering)
throws Exception
{
long start = System.nanoTime();
MaterializedResult actualResults = computeActual(actual);
log.info("FINISHED in %s", Duration.nanosSince(start));
MaterializedResult expectedResults = computeExpected(expected, actualResults.getTupleInfo());
if (ensureOrdering) {
assertEquals(actualResults.getMaterializedTuples(), expectedResults.getMaterializedTuples());
}
else {
assertEqualsIgnoreOrder(actualResults.getMaterializedTuples(), expectedResults.getMaterializedTuples());
}
}
public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected)
{
assertNotNull(actual, "actual is null");
assertNotNull(expected, "expected is null");
ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual);
ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected);
if (!actualSet.equals(expectedSet)) {
fail(format("not equal\nActual %s rows:\n %s\nExpected %s rows:\n %s\n",
actualSet.size(),
Joiner.on("\n ").join(Iterables.limit(actualSet, 100)),
expectedSet.size(),
Joiner.on("\n ").join(Iterables.limit(expectedSet, 100))));
}
}
private MaterializedResult computeExpected(@Language("SQL") final String sql, TupleInfo resultTupleInfo)
{
return new MaterializedResult(
handle.createQuery(sql)
.map(tupleMapper(resultTupleInfo))
.list(),
resultTupleInfo
);
}
private static ResultSetMapper<Tuple> tupleMapper(final TupleInfo tupleInfo)
{
return new ResultSetMapper<Tuple>()
{
@Override
public Tuple map(int index, ResultSet resultSet, StatementContext ctx)
throws SQLException
{
List<TupleInfo.Type> types = tupleInfo.getTypes();
int count = resultSet.getMetaData().getColumnCount();
checkArgument(types.size() == count, "tuple info does not match result");
TupleInfo.Builder builder = tupleInfo.builder();
for (int i = 1; i <= count; i++) {
TupleInfo.Type type = types.get(i - 1);
switch (type) {
case FIXED_INT_64:
long longValue = resultSet.getLong(i);
if (resultSet.wasNull()) {
builder.appendNull();
}
else {
builder.append(longValue);
}
break;
case DOUBLE:
double doubleValue = resultSet.getDouble(i);
if (resultSet.wasNull()) {
builder.appendNull();
}
else {
builder.append(doubleValue);
}
break;
case VARIABLE_BINARY:
String value = resultSet.getString(i);
if (resultSet.wasNull()) {
builder.appendNull();
}
else {
builder.append(Slices.wrappedBuffer(value.getBytes(UTF_8)));
}
break;
default:
throw new AssertionError("unhandled type: " + type);
}
}
return builder.build();
}
};
}
private static void insertRows(TableMetadata tableMetadata, Handle handle, RecordSet data)
{
String vars = Joiner.on(',').join(nCopies(tableMetadata.getColumns().size(), "?"));
String sql = format("INSERT INTO %s VALUES (%s)", tableMetadata.getTable().getTableName(), vars);
RecordCursor cursor = data.cursor();
while (true) {
// insert 1000 rows at a time
PreparedBatch batch = handle.prepareBatch(sql);
for (int row = 0; row < 1000; row++) {
if (!cursor.advanceNextPosition()) {
batch.execute();
return;
}
PreparedBatchPart part = batch.add();
for (int column = 0; column < tableMetadata.getColumns().size(); column++) {
ColumnMetadata columnMetadata = tableMetadata.getColumns().get(column);
switch (columnMetadata.getType()) {
case LONG:
part.bind(column, cursor.getLong(column));
break;
case DOUBLE:
part.bind(column, cursor.getDouble(column));
break;
case STRING:
part.bind(column, new String(cursor.getString(column), UTF_8));
break;
}
}
}
batch.execute();
}
}
private Function<MaterializedTuple, String> onlyColumnGetter()
{
return new Function<MaterializedTuple, String>()
{
@Override
public String apply(MaterializedTuple input)
{
assertEquals(input.getFieldCount(), 1);
return (String) input.getField(0);
}
};
}
}
|
presto-main/src/test/java/com/facebook/presto/AbstractTestQueries.java
|
package com.facebook.presto;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.RecordCursor;
import com.facebook.presto.spi.RecordSet;
import com.facebook.presto.spi.TableMetadata;
import com.facebook.presto.tpch.TpchMetadata;
import com.facebook.presto.tuple.Tuple;
import com.facebook.presto.tuple.TupleInfo;
import com.facebook.presto.util.MaterializedResult;
import com.facebook.presto.util.MaterializedTuple;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimaps;
import io.airlift.log.Logger;
import io.airlift.log.Logging;
import io.airlift.slice.Slices;
import io.airlift.units.Duration;
import org.intellij.lang.annotations.Language;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.PreparedBatch;
import org.skife.jdbi.v2.PreparedBatchPart;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_LINEITEM_METADATA;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_LINEITEM_NAME;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_ORDERS_METADATA;
import static com.facebook.presto.tpch.TpchMetadata.TPCH_ORDERS_NAME;
import static com.facebook.presto.tuple.TupleInfo.Type.DOUBLE;
import static com.facebook.presto.tuple.TupleInfo.Type.FIXED_INT_64;
import static com.facebook.presto.tuple.TupleInfo.Type.VARIABLE_BINARY;
import static com.facebook.presto.util.InMemoryTpchBlocksProvider.readTpchRecords;
import static com.facebook.presto.util.MaterializedResult.resultBuilder;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.transform;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
public abstract class AbstractTestQueries
{
private Handle handle;
@Test
public void testComplexQuery()
throws Exception
{
MaterializedResult actual = computeActual("SELECT sum(orderkey), row_number() OVER (ORDER BY orderkey)\n" +
"FROM orders\n" +
"WHERE orderkey <= 10\n" +
"GROUP BY orderkey\n" +
"HAVING sum(orderkey) >= 3\n" +
"ORDER BY orderkey DESC\n" +
"LIMIT 3");
MaterializedResult expected = resultBuilder(FIXED_INT_64, FIXED_INT_64)
.row(7, 5)
.row(6, 4)
.row(5, 3)
.build();
assertEquals(actual, expected);
}
@Test
public void testSumOfNulls()
throws Exception
{
assertQuery("SELECT orderstatus, sum(CAST(NULL AS BIGINT)) FROM orders GROUP BY orderstatus");
}
@Test
public void testApproximateCountDistinct()
throws Exception
{
MaterializedResult actual = computeActual("SELECT approx_distinct(custkey) FROM orders");
MaterializedResult expected = resultBuilder(FIXED_INT_64)
.row(971)
.build();
assertEqualsIgnoreOrder(actual.getMaterializedTuples(), expected.getMaterializedTuples());
}
@Test
public void testApproximateCountDistinctGroupBy()
throws Exception
{
MaterializedResult actual = computeActual("SELECT orderstatus, approx_distinct(custkey) FROM orders GROUP BY orderstatus");
MaterializedResult expected = resultBuilder(actual.getTupleInfo())
.row("O", 969)
.row("F", 964)
.row("P", 301)
.build();
assertEqualsIgnoreOrder(actual.getMaterializedTuples(), expected.getMaterializedTuples());
}
@Test
public void testJoinWithMultiFieldGroupBy()
throws Exception
{
assertQuery("SELECT orderstatus FROM lineitem JOIN (SELECT DISTINCT orderkey, orderstatus FROM ORDERS) T on lineitem.orderkey = T.orderkey");
}
@Test
public void testGroupByMultipleFieldsWithPredicateOnAggregationArgument()
throws Exception
{
assertQuery("SELECT custkey, orderstatus, MAX(orderkey) FROM ORDERS WHERE orderkey = 1 GROUP BY custkey, orderstatus");
}
@Test
public void testReorderOutputsOfGroupByAggregation()
throws Exception
{
assertQuery(
"SELECT orderstatus, a, custkey, b FROM (SELECT custkey, orderstatus, -COUNT(*) a, MAX(orderkey) b FROM ORDERS WHERE orderkey = 1 GROUP BY custkey, orderstatus) T");
}
@Test
public void testGroupAggregationOverNestedGroupByAggregation()
throws Exception
{
assertQuery("SELECT sum(custkey), max(orderstatus), min(c) FROM (SELECT orderstatus, custkey, COUNT(*) c FROM ORDERS GROUP BY orderstatus, custkey) T");
}
@Test
public void testDistinctMultipleFields()
throws Exception
{
assertQuery("SELECT DISTINCT custkey, orderstatus FROM ORDERS");
}
@Test
public void testArithmeticNegation()
throws Exception
{
assertQuery("SELECT -custkey FROM orders");
}
@Test
public void testDistinct()
throws Exception
{
assertQuery("SELECT DISTINCT custkey FROM orders");
}
// TODO: we need to properly propagate exceptions with their actual classes
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = "DISTINCT in aggregation parameters not yet supported")
public void testCountDistinct()
throws Exception
{
assertQuery("SELECT COUNT(DISTINCT custkey) FROM orders");
}
@Test
public void testDistinctWithOrderBy()
throws Exception
{
assertQuery("SELECT DISTINCT custkey FROM orders ORDER BY custkey LIMIT 10");
}
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = "For SELECT DISTINCT, ORDER BY expressions must appear in select list")
public void testDistinctWithOrderByNotInSelect()
throws Exception
{
assertQuery("SELECT DISTINCT custkey FROM orders ORDER BY orderkey LIMIT 10");
}
@Test
public void testOrderByLimit()
throws Exception
{
assertQueryOrdered("SELECT custkey, orderstatus FROM ORDERS ORDER BY orderkey DESC LIMIT 10");
}
@Test
public void testOrderByExpressionWithLimit()
throws Exception
{
assertQueryOrdered("SELECT custkey, orderstatus FROM ORDERS ORDER BY orderkey + 1 DESC LIMIT 10");
}
@Test
public void testGroupByOrderByLimit()
throws Exception
{
assertQueryOrdered("SELECT custkey, SUM(totalprice) FROM ORDERS GROUP BY custkey ORDER BY SUM(totalprice) DESC LIMIT 10");
}
@Test
public void testLimitZero()
throws Exception
{
assertQuery("SELECT custkey, totalprice FROM orders LIMIT 0");
}
@Test
public void testRepeatedAggregations()
throws Exception
{
assertQuery("SELECT SUM(orderkey), SUM(orderkey) FROM ORDERS");
}
@Test
public void testRepeatedOutputs()
throws Exception
{
assertQuery("SELECT orderkey a, orderkey b FROM ORDERS WHERE orderstatus = 'F'");
}
@Test
public void testLimit()
throws Exception
{
MaterializedResult actual = computeActual("SELECT orderkey FROM ORDERS LIMIT 10");
MaterializedResult all = computeExpected("SELECT orderkey FROM ORDERS", actual.getTupleInfo());
assertEquals(actual.getMaterializedTuples().size(), 10);
assertTrue(all.getMaterializedTuples().containsAll(actual.getMaterializedTuples()));
}
@Test
public void testAggregationWithLimit()
throws Exception
{
MaterializedResult actual = computeActual("SELECT custkey, SUM(totalprice) FROM ORDERS GROUP BY custkey LIMIT 10");
MaterializedResult all = computeExpected("SELECT custkey, SUM(totalprice) FROM ORDERS GROUP BY custkey", actual.getTupleInfo());
assertEquals(actual.getMaterializedTuples().size(), 10);
assertTrue(all.getMaterializedTuples().containsAll(actual.getMaterializedTuples()));
}
@Test
public void testLimitInInlineView()
throws Exception
{
MaterializedResult actual = computeActual("SELECT orderkey FROM (SELECT orderkey FROM ORDERS LIMIT 100) T LIMIT 10");
MaterializedResult all = computeExpected("SELECT orderkey FROM ORDERS", actual.getTupleInfo());
assertEquals(actual.getMaterializedTuples().size(), 10);
assertTrue(all.getMaterializedTuples().containsAll(actual.getMaterializedTuples()));
}
@Test
public void testCountAll()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM ORDERS");
}
@Test
public void testCountColumn()
throws Exception
{
assertQuery("SELECT COUNT(orderkey) FROM ORDERS");
assertQuery("SELECT COUNT(orderstatus) FROM ORDERS");
assertQuery("SELECT COUNT(orderdate) FROM ORDERS");
assertQuery("SELECT COUNT(1) FROM ORDERS");
assertQuery("SELECT COUNT(NULLIF(orderstatus, 'F')) FROM ORDERS");
assertQuery("SELECT COUNT(CAST(NULL AS BIGINT)) FROM ORDERS"); // todo: make COUNT(null) work
}
@Test
public void testWildcard()
throws Exception
{
assertQuery("SELECT * FROM ORDERS");
}
@Test
public void testMultipleWildcards()
throws Exception
{
assertQuery("SELECT *, 123, * FROM ORDERS");
}
@Test
public void testMixedWildcards()
throws Exception
{
assertQuery("SELECT *, orders.*, orderkey FROM orders");
}
@Test
public void testQualifiedWildcardFromAlias()
throws Exception
{
assertQuery("SELECT T.* FROM ORDERS T");
}
@Test
public void testQualifiedWildcardFromInlineView()
throws Exception
{
assertQuery("SELECT T.* FROM (SELECT orderkey + custkey FROM ORDERS) T");
}
@Test
public void testQualifiedWildcard()
throws Exception
{
assertQuery("SELECT ORDERS.* FROM ORDERS");
}
@Test
public void testAverageAll()
throws Exception
{
assertQuery("SELECT AVG(totalprice) FROM ORDERS");
}
@Test
public void testVariance()
throws Exception
{
// int64
assertQuery("SELECT VAR_SAMP(custkey) FROM ORDERS");
assertQuery("SELECT VAR_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT VAR_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT VAR_SAMP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT VAR_SAMP(totalprice) FROM ORDERS");
assertQuery("SELECT VAR_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT VAR_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT VAR_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testVariancePop()
throws Exception
{
// int64
assertQuery("SELECT VAR_POP(custkey) FROM ORDERS");
assertQuery("SELECT VAR_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT VAR_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT VAR_POP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT VAR_POP(totalprice) FROM ORDERS");
assertQuery("SELECT VAR_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT VAR_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT VAR_POP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testStdDev()
throws Exception
{
// int64
assertQuery("SELECT STDDEV_SAMP(custkey) FROM ORDERS");
assertQuery("SELECT STDDEV_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT STDDEV_SAMP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT STDDEV_SAMP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM ORDERS");
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT STDDEV_SAMP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testStdDevPop()
throws Exception
{
// int64
assertQuery("SELECT STDDEV_POP(custkey) FROM ORDERS");
assertQuery("SELECT STDDEV_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 2) T");
assertQuery("SELECT STDDEV_POP(custkey) FROM (SELECT custkey FROM ORDERS ORDER BY custkey LIMIT 1) T");
assertQuery("SELECT STDDEV_POP(custkey) FROM (SELECT custkey FROM ORDERS LIMIT 0) T");
// double
assertQuery("SELECT STDDEV_POP(totalprice) FROM ORDERS");
assertQuery("SELECT STDDEV_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 2) T");
assertQuery("SELECT STDDEV_POP(totalprice) FROM (SELECT totalprice FROM ORDERS ORDER BY totalprice LIMIT 1) T");
assertQuery("SELECT STDDEV_POP(totalprice) FROM (SELECT totalprice FROM ORDERS LIMIT 0) T");
}
@Test
public void testCountAllWithPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM ORDERS WHERE orderstatus = 'F'");
}
@Test
public void testGroupByNoAggregations()
throws Exception
{
assertQuery("SELECT custkey FROM ORDERS GROUP BY custkey");
}
@Test
public void testGroupByCount()
throws Exception
{
assertQuery(
"SELECT orderstatus, COUNT(*) FROM ORDERS GROUP BY orderstatus",
"SELECT orderstatus, CAST(COUNT(*) AS INTEGER) FROM orders GROUP BY orderstatus"
);
}
@Test
public void testGroupByMultipleFields()
throws Exception
{
assertQuery("SELECT custkey, orderstatus, COUNT(*) FROM ORDERS GROUP BY custkey, orderstatus");
}
@Test
public void testGroupByWithAlias()
throws Exception
{
assertQuery(
"SELECT orderdate x, COUNT(*) FROM orders GROUP BY orderdate",
"SELECT orderdate x, CAST(COUNT(*) AS INTEGER) FROM orders GROUP BY orderdate"
);
}
@Test
public void testGroupBySum()
throws Exception
{
assertQuery("SELECT orderstatus, SUM(totalprice) FROM ORDERS GROUP BY orderstatus");
}
@Test
public void testGroupByWithWildcard()
throws Exception
{
assertQuery("SELECT * FROM (SELECT orderkey FROM orders) t GROUP BY orderkey");
}
@Test
public void testCountAllWithComparison()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE tax < discount");
}
@Test
public void testSelectWithComparison()
throws Exception
{
assertQuery("SELECT orderkey FROM lineitem WHERE tax < discount");
}
@Test
public void testCountWithNotPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE NOT tax < discount");
}
@Test
public void testCountWithNullPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE NULL");
}
@Test
public void testCountWithIsNullPredicate()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM orders WHERE NULLIF(orderstatus, 'F') IS NULL",
"SELECT COUNT(*) FROM orders WHERE orderstatus = 'F' "
);
}
@Test
public void testCountWithIsNotNullPredicate()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM orders WHERE NULLIF(orderstatus, 'F') IS NOT NULL",
"SELECT COUNT(*) FROM orders WHERE orderstatus <> 'F' "
);
}
@Test
public void testCountWithNullIfPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM orders WHERE NULLIF(orderstatus, 'F') = orderstatus ");
}
@Test
public void testCountWithCoalescePredicate()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM orders WHERE COALESCE(NULLIF(orderstatus, 'F'), 'bar') = 'bar'",
"SELECT COUNT(*) FROM orders WHERE orderstatus = 'F'"
);
}
@Test
public void testCountWithAndPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE tax < discount AND tax > 0.01 AND discount < 0.05");
}
@Test
public void testCountWithOrPredicate()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem WHERE tax < 0.01 OR discount > 0.05");
}
@Test
public void testCountWithInlineView()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM (SELECT orderkey FROM lineitem) x");
}
@Test
public void testNestedCount()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM (SELECT orderkey, COUNT(*) FROM lineitem GROUP BY orderkey) x");
}
@Test
public void testAggregationWithProjection()
throws Exception
{
assertQuery("SELECT sum(totalprice * 2) - sum(totalprice) FROM orders");
}
@Test
public void testAggregationWithProjection2()
throws Exception
{
assertQuery("SELECT sum(totalprice * 2) + sum(totalprice * 2) FROM orders");
}
@Test
public void testInlineView()
throws Exception
{
assertQuery("SELECT orderkey, custkey FROM (SELECT orderkey, custkey FROM ORDERS) U");
}
@Test
public void testAliasedInInlineView()
throws Exception
{
assertQuery("SELECT x, y FROM (SELECT orderkey x, custkey y FROM ORDERS) U");
}
@Test
public void testGroupByWithoutAggregation()
throws Exception
{
assertQuery("SELECT orderstatus FROM orders GROUP BY orderstatus");
}
@Test
public void testHistogram()
throws Exception
{
assertQuery("SELECT lines, COUNT(*) FROM (SELECT orderkey, COUNT(*) lines FROM lineitem GROUP BY orderkey) U GROUP BY lines");
}
@Test
public void testSimpleJoin()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey");
}
@Test
public void testJoinWithAlias()
throws Exception
{
assertQuery("SELECT * FROM (lineitem JOIN orders ON lineitem.orderkey = orders.orderkey) x");
}
@Test
public void testJoinWithConstantExpression()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND 123 = 123");
}
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = ".*not supported.*")
public void testJoinOnConstantExpression()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON 123 = 123");
}
@Test
public void testJoinUsing()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM lineitem join orders using (orderkey)",
"SELECT COUNT(*) FROM lineitem join orders on lineitem.orderkey = orders.orderkey"
);
}
@Test
public void testJoinWithReversedComparison()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON orders.orderkey = lineitem.orderkey");
}
@Test
public void testJoinWithComplexExpressions()
throws Exception
{
assertQuery("SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey = CAST(orders.orderkey AS BIGINT)");
}
@Test
public void testJoinWithComplexExpressions2()
throws Exception
{
assertQuery(
"SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey = CASE WHEN orders.custkey = 1 and orders.orderstatus = 'F' THEN orders.orderkey ELSE NULL END");
}
@Test
public void testJoinWithComplexExpressions3()
throws Exception
{
assertQuery(
"SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey + 1 = orders.orderkey + 1",
"SELECT SUM(custkey) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey "
// H2 takes a million years because it can't join efficiently on a non-indexed field/expression
);
}
@Test
public void testSelfJoin()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM orders a JOIN orders b on a.orderkey = b.orderkey");
}
@Test
public void testWildcardFromJoin()
throws Exception
{
assertQuery(
"SELECT * FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b using (orderkey)",
"SELECT * FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b on a.orderkey = b.orderkey"
);
}
@Test
public void testQualifiedWildcardFromJoin()
throws Exception
{
assertQuery(
"SELECT a.*, b.* FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b using (orderkey)",
"SELECT a.*, b.* FROM (select orderkey, partkey from lineitem) a join (select orderkey, custkey from orders) b on a.orderkey = b.orderkey"
);
}
@Test
public void testJoinAggregations()
throws Exception
{
assertQuery(
"SELECT x + y FROM (" +
" SELECT orderdate, COUNT(*) x FROM orders GROUP BY orderdate) a JOIN (" +
" SELECT orderdate, COUNT(*) y FROM orders GROUP BY orderdate) b ON a.orderdate = b.orderdate");
}
@Test
public void testJoinOnMultipleFields()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND lineitem.shipdate = orders.orderdate");
}
@Test
public void testJoinUsingMultipleFields()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM lineitem JOIN (SELECT orderkey, orderdate shipdate FROM ORDERS) T USING (orderkey, shipdate)",
"SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND lineitem.shipdate = orders.orderdate"
);
}
@Test
public void testJoinWithNonJoinExpression()
throws Exception
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.custkey = 1");
}
@Test
public void testOrderBy()
throws Exception
{
assertQueryOrdered("SELECT orderstatus FROM orders ORDER BY orderstatus");
}
@Test
public void testOrderBy2()
throws Exception
{
assertQueryOrdered("SELECT orderstatus FROM orders ORDER BY orderkey DESC");
}
@Test
public void testOrderByMultipleFields()
throws Exception
{
assertQuery("SELECT orderkey, orderstatus FROM orders ORDER BY custkey DESC, orderstatus");
}
@Test
public void testOrderByAlias()
throws Exception
{
assertQueryOrdered("SELECT orderstatus x FROM orders ORDER BY x ASC");
}
@Test
public void testOrderByAliasWithSameNameAsUnselectedColumn()
throws Exception
{
assertQueryOrdered("SELECT orderstatus orderdate FROM orders ORDER BY orderdate ASC");
}
@Test
public void testOrderByOrdinal()
throws Exception
{
assertQueryOrdered("SELECT orderstatus, orderdate FROM orders ORDER BY 2, 1");
}
@Test
public void testOrderByOrdinalWithWildcard()
throws Exception
{
assertQueryOrdered("SELECT * FROM orders ORDER BY 1");
}
@Test
public void testGroupByOrdinal()
throws Exception
{
assertQuery(
"SELECT orderstatus, sum(totalprice) FROM orders GROUP BY 1",
"SELECT orderstatus, sum(totalprice) FROM orders GROUP BY orderstatus");
}
@Test
public void testGroupBySearchedCase()
throws Exception
{
assertQuery("SELECT CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END");
assertQuery(
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY 1",
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' ELSE 'b' END");
}
@Test
public void testGroupBySearchedCaseNoElse()
throws Exception
{
// whole CASE in group by clause
assertQuery("SELECT CASE WHEN orderstatus = 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' END");
assertQuery(
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY 1",
"SELECT CASE WHEN orderstatus = 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderstatus = 'O' THEN 'a' END");
assertQuery("SELECT CASE WHEN true THEN orderstatus END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
}
@Test
public void testGroupByCase()
throws Exception
{
// whole CASE in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END");
assertQuery(
"SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY 1",
"SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END");
// operand in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// condition in group by clause
assertQuery("SELECT CASE 'O' WHEN orderstatus THEN 'a' ELSE 'b' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// 'then' in group by clause
assertQuery("SELECT CASE 1 WHEN 1 THEN orderstatus ELSE 'x' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// 'else' in group by clause
assertQuery("SELECT CASE 1 WHEN 1 THEN 'x' ELSE orderstatus END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
}
@Test
public void testGroupByCaseNoElse()
throws Exception
{
// whole CASE in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY CASE orderstatus WHEN 'O' THEN 'a' END");
// operand in group by clause
assertQuery("SELECT CASE orderstatus WHEN 'O' THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// condition in group by clause
assertQuery("SELECT CASE 'O' WHEN orderstatus THEN 'a' END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
// 'then' in group by clause
assertQuery("SELECT CASE 1 WHEN 1 THEN orderstatus END, count(*)\n" +
"FROM orders\n" +
"GROUP BY orderstatus");
}
@Test
public void testGroupByCast()
throws Exception
{
// whole CAST in group by expression
assertQuery("SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY CAST(orderkey AS VARCHAR)");
assertQuery(
"SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY 1",
"SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY CAST(orderkey AS VARCHAR)");
// argument in group by expression
assertQuery("SELECT CAST(orderkey AS VARCHAR), count(*) FROM orders GROUP BY orderkey");
}
@Test
public void testGroupByCoalesce()
throws Exception
{
// whole COALESCE in group by
assertQuery("SELECT COALESCE(orderkey, custkey), count(*) FROM orders GROUP BY COALESCE(orderkey, custkey)");
assertQuery(
"SELECT COALESCE(orderkey, custkey), count(*) FROM orders GROUP BY 1",
"SELECT COALESCE(orderkey, custkey), count(*) FROM orders GROUP BY COALESCE(orderkey, custkey)"
);
// operands in group by
assertQuery("SELECT COALESCE(orderkey, 1), count(*) FROM orders GROUP BY orderkey");
// operands in group by
assertQuery("SELECT COALESCE(1, orderkey), count(*) FROM orders GROUP BY orderkey");
}
@Test
public void testGroupByNullIf()
throws Exception
{
// whole NULLIF in group by
assertQuery("SELECT NULLIF(orderkey, custkey), count(*) FROM orders GROUP BY NULLIF(orderkey, custkey)");
assertQuery(
"SELECT NULLIF(orderkey, custkey), count(*) FROM orders GROUP BY 1",
"SELECT NULLIF(orderkey, custkey), count(*) FROM orders GROUP BY NULLIF(orderkey, custkey)");
// first operand in group by
assertQuery("SELECT NULLIF(orderkey, 1), count(*) FROM orders GROUP BY orderkey");
// second operand in group by
assertQuery("SELECT NULLIF(1, orderkey), count(*) FROM orders GROUP BY orderkey");
}
@Test
public void testGroupByExtract()
throws Exception
{
// whole expression in group by
assertQuery("SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY EXTRACT(YEAR FROM now())");
assertQuery(
"SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY 1",
"SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY EXTRACT(YEAR FROM now())");
// argument in group by
assertQuery("SELECT EXTRACT(YEAR FROM now()), count(*) FROM orders GROUP BY now()");
}
@Test
public void testGroupByBetween()
throws Exception
{
// whole expression in group by
// TODO: enable once we support booleans
// assertQuery("SELECT orderkey BETWEEN 1 AND 100 FROM orders GROUP BY orderkey BETWEEN 1 AND 100 ");
// expression in group by
assertQuery("SELECT CAST(orderkey BETWEEN 1 AND 100 AS BIGINT) FROM orders GROUP BY orderkey");
// min in group by
assertQuery("SELECT CAST(50 BETWEEN orderkey AND 100 AS BIGINT) FROM orders GROUP BY orderkey");
// max in group by
assertQuery("SELECT CAST(50 BETWEEN 1 AND orderkey AS BIGINT) FROM orders GROUP BY orderkey");
}
@Test
public void testHaving()
throws Exception
{
assertQuery("SELECT orderstatus, sum(totalprice) FROM orders GROUP BY orderstatus HAVING orderstatus = 'O'");
}
@Test
public void testHaving2()
throws Exception
{
assertQuery("SELECT custkey, sum(orderkey) FROM orders GROUP BY custkey HAVING sum(orderkey) > 400000");
}
@Test
public void testHaving3()
throws Exception
{
assertQuery("SELECT custkey, sum(totalprice) * 2 FROM orders GROUP BY custkey HAVING avg(totalprice + 5) > 10");
}
@Test
public void testColumnAliases()
throws Exception
{
assertQuery(
"SELECT x, T.y, z + 1 FROM (SELECT custkey, orderstatus, totalprice FROM orders) T (x, y, z)",
"SELECT custkey, orderstatus, totalprice + 1 FROM orders");
}
@Test
public void testSameInputToAggregates()
throws Exception
{
assertQuery("SELECT max(a), max(b) FROM (SELECT custkey a, custkey b FROM orders) x");
}
@SuppressWarnings("PointlessArithmeticExpression")
@Test
public void testWindowFunctionsExpressions()
{
MaterializedResult actual = computeActual("" +
"SELECT orderkey, orderstatus\n" +
", row_number() OVER (ORDER BY orderkey * 2) *\n" +
" row_number() OVER (ORDER BY orderkey DESC) + 100\n" +
"FROM (SELECT * FROM orders ORDER BY orderkey LIMIT 10) x\n" +
"ORDER BY orderkey LIMIT 5");
MaterializedResult expected = resultBuilder(FIXED_INT_64, VARIABLE_BINARY, FIXED_INT_64)
.row(1, "O", (1 * 10) + 100)
.row(2, "O", (2 * 9) + 100)
.row(3, "F", (3 * 8) + 100)
.row(4, "O", (4 * 7) + 100)
.row(5, "F", (5 * 6) + 100)
.build();
assertEquals(actual, expected);
}
@Test
public void testWindowFunctionsFromAggregate()
throws Exception
{
MaterializedResult actual = computeActual("" +
"SELECT * FROM (\n" +
" SELECT orderstatus, clerk, sales\n" +
" , rank() OVER (PARTITION BY x.orderstatus ORDER BY sales DESC) rnk\n" +
" FROM (\n" +
" SELECT orderstatus, clerk, sum(totalprice) sales\n" +
" FROM orders\n" +
" GROUP BY orderstatus, clerk\n" +
" ) x\n" +
") x\n" +
"WHERE rnk <= 2\n" +
"ORDER BY orderstatus, rnk");
MaterializedResult expected = resultBuilder(VARIABLE_BINARY, VARIABLE_BINARY, DOUBLE, FIXED_INT_64)
.row("F", "Clerk#000000090", 2784836.61, 1)
.row("F", "Clerk#000000084", 2674447.15, 2)
.row("O", "Clerk#000000500", 2569878.29, 1)
.row("O", "Clerk#000000050", 2500162.92, 2)
.row("P", "Clerk#000000071", 841820.99, 1)
.row("P", "Clerk#000001000", 643679.49, 2)
.build();
assertEquals(actual, expected);
}
@Test
public void testOrderByWindowFunction()
throws Exception
{
MaterializedResult actual = computeActual("" +
"SELECT orderkey, row_number() OVER (ORDER BY orderkey)\n" +
"FROM (SELECT * FROM orders ORDER BY orderkey LIMIT 10)\n" +
"ORDER BY 2 DESC\n" +
"LIMIT 5");
MaterializedResult expected = resultBuilder(FIXED_INT_64, FIXED_INT_64)
.row(34, 10)
.row(33, 9)
.row(32, 8)
.row(7, 7)
.row(6, 6)
.build();
assertEquals(actual, expected);
}
@Test
public void testScalarFunction()
throws Exception
{
assertQuery("SELECT SUBSTR('Quadratically', 5, 6) FROM orders LIMIT 1");
}
@Test
public void testCast()
throws Exception
{
assertQuery("SELECT CAST(totalprice AS BIGINT) FROM orders");
assertQuery("SELECT CAST(orderkey AS DOUBLE) FROM orders");
assertQuery("SELECT CAST(orderkey AS VARCHAR) FROM orders");
}
@Test
public void testConcatOperator()
throws Exception
{
assertQuery("SELECT '12' || '34' FROM orders LIMIT 1");
}
@Test
public void testQuotedIdentifiers()
throws Exception
{
assertQuery("SELECT \"TOTALPRICE\" \"my price\" FROM \"ORDERS\"");
}
@Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = ".*orderkey_1.*")
public void testInvalidColumn()
throws Exception
{
computeActual("select * from lineitem l join (select orderkey_1, custkey from orders) o on l.orderkey = o.orderkey_1");
}
@Test
public void testUnaliasedSubqueries()
throws Exception
{
assertQuery("SELECT orderkey FROM (SELECT orderkey FROM orders)");
}
@Test
public void testUnaliasedSubqueries1()
throws Exception
{
assertQuery("SELECT a FROM (SELECT orderkey a FROM orders)");
}
@Test
public void testJoinUnaliasedSubqueries()
throws Exception
{
assertQuery(
"SELECT COUNT(*) FROM (SELECT * FROM lineitem) join (SELECT * FROM orders) using (orderkey)",
"SELECT COUNT(*) FROM lineitem join orders on lineitem.orderkey = orders.orderkey"
);
}
@Test
public void testWith()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT * FROM orders) " +
"SELECT * FROM a",
"SELECT * FROM orders");
}
@Test
public void testWithQualifiedPrefix()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT 123 FROM orders LIMIT 1)" +
"SELECT a.* FROM a",
"SELECT 123 FROM orders LIMIT 1");
}
@Test
public void testWithAliased()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT * FROM orders) " +
"SELECT * FROM a x",
"SELECT * FROM orders");
}
@Test
public void testReferenceToWithQueryInFromClause()
throws Exception
{
assertQuery(
"WITH a AS (SELECT * FROM orders)" +
"SELECT * FROM (" +
" SELECT * FROM a" +
")",
"SELECT * FROM orders");
}
@Test
public void testWithChaining()
throws Exception
{
assertQuery("" +
"WITH a AS (SELECT orderkey n FROM orders)\n" +
", b AS (SELECT n + 1 n FROM a)\n" +
", c AS (SELECT n + 1 n FROM b)\n" +
"SELECT n + 1 FROM c",
"SELECT orderkey + 3 FROM orders");
}
@Test
public void testWithSelfJoin()
throws Exception
{
assertQuery("" +
"WITH x AS (SELECT DISTINCT orderkey FROM orders ORDER BY orderkey LIMIT 10)\n" +
"SELECT count(*) FROM x a JOIN x b USING (orderkey)", "" +
"SELECT count(*)\n" +
"FROM (SELECT DISTINCT orderkey FROM orders ORDER BY orderkey LIMIT 10) a\n" +
"JOIN (SELECT DISTINCT orderkey FROM orders ORDER BY orderkey LIMIT 10) b ON a.orderkey = b.orderkey");
}
@Test
public void testWithNestedSubqueries()
throws Exception
{
assertQuery("" +
"WITH a AS (\n" +
" WITH aa AS (SELECT 123 x FROM orders LIMIT 1)\n" +
" SELECT x y FROM aa\n" +
"), b AS (\n" +
" WITH bb AS (\n" +
" WITH bbb AS (SELECT y FROM a)\n" +
" SELECT bbb.* FROM bbb\n" +
" )\n" +
" SELECT y z FROM bb\n" +
")\n" +
"SELECT *\n" +
"FROM (\n" +
" WITH q AS (SELECT z w FROM b)\n" +
" SELECT j.*, k.*\n" +
" FROM a j\n" +
" JOIN q k ON (j.y = k.w)\n" +
") t", "" +
"SELECT 123, 123 FROM orders LIMIT 1");
}
@Test(enabled = false)
public void testWithColumnAliasing()
throws Exception
{
assertQuery(
"WITH a (id) AS (SELECT 123 FROM orders LIMIT 1) SELECT * FROM a",
"SELECT 123 FROM orders LIMIT 1");
}
@Test
public void testWithHiding()
throws Exception
{
assertQuery(
"WITH a AS (SELECT custkey FROM orders), " +
" b AS (" +
" WITH a AS (SELECT orderkey FROM orders)" +
" SELECT * FROM a" + // should refer to inner 'a'
" )" +
"SELECT * FROM b",
"SELECT orderkey FROM orders"
);
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Recursive WITH queries are not supported")
public void testWithRecursive()
throws Exception
{
computeActual("WITH RECURSIVE a AS (SELECT 123 FROM dual) SELECT * FROM a");
}
@Test
public void testCaseNoElse()
throws Exception
{
assertQuery("SELECT orderkey, CASE orderstatus WHEN 'O' THEN 'a' END FROM orders");
}
@Test
public void testIfExpression()
throws Exception
{
assertQuery(
"SELECT sum(IF(orderstatus = 'F', totalprice, 0.0)) FROM orders",
"SELECT sum(CASE WHEN orderstatus = 'F' THEN totalprice ELSE 0.0 END) FROM orders");
assertQuery(
"SELECT sum(IF(orderstatus = 'Z', totalprice)) FROM orders",
"SELECT sum(CASE WHEN orderstatus = 'Z' THEN totalprice END) FROM orders");
assertQuery(
"SELECT sum(IF(orderstatus = 'F', NULL, totalprice)) FROM orders",
"SELECT sum(CASE WHEN orderstatus = 'F' THEN NULL ELSE totalprice END) FROM orders");
assertQuery(
"SELECT IF(orderstatus = 'Z', orderkey / 0, orderkey) FROM orders",
"SELECT CASE WHEN orderstatus = 'Z' THEN orderkey / 0 ELSE orderkey END FROM orders");
assertQuery(
"SELECT sum(IF(NULLIF(orderstatus, 'F') <> 'F', totalprice, 5.1)) FROM orders",
"SELECT sum(CASE WHEN NULLIF(orderstatus, 'F') <> 'F' THEN totalprice ELSE 5.1 END) FROM orders");
}
@Test
public void testIn()
throws Exception
{
assertQuery("SELECT orderkey FROM orders WHERE orderkey IN (1, 2, 3)");
assertQuery("SELECT orderkey FROM orders WHERE orderkey IN (1.5, 2.3)");
assertQuery("SELECT orderkey FROM orders WHERE totalprice IN (1, 2, 3)");
}
@Test
public void testGroupByIf()
throws Exception
{
assertQuery(
"SELECT IF(orderkey between 1 and 5, 'orders', 'others'), sum(totalprice) FROM orders GROUP BY 1",
"SELECT CASE WHEN orderkey BETWEEN 1 AND 5 THEN 'orders' ELSE 'others' END, sum(totalprice)\n" +
"FROM orders\n" +
"GROUP BY CASE WHEN orderkey BETWEEN 1 AND 5 THEN 'orders' ELSE 'others' END");
}
@Test
public void testDuplicateFields()
throws Exception
{
assertQuery(
"SELECT * FROM (SELECT orderkey, orderkey FROM orders)",
"SELECT orderkey, orderkey FROM orders");
}
@Test
public void testWildcardFromSubquery()
throws Exception
{
assertQuery("SELECT * FROM (SELECT orderkey X FROM orders)");
}
@Test
public void testCaseInsensitiveOutputAliasInOrderBy()
throws Exception
{
assertQuery("SELECT orderkey X FROM orders ORDER BY x");
}
@Test
public void testCaseInsensitiveAttribute()
throws Exception
{
assertQuery("SELECT x FROM (SELECT orderkey X FROM orders)");
}
@Test
public void testCaseInsensitiveAliasedRelation()
throws Exception
{
assertQuery("SELECT A.* FROM orders a");
}
@Test
public void testSubqueryBody()
throws Exception
{
assertQuery("(SELECT orderkey, custkey FROM ORDERS)");
}
@Test
public void testSubqueryBodyOrderLimit()
throws Exception
{
assertQuery("(SELECT orderkey AS a, custkey AS b FROM ORDERS) ORDER BY a LIMIT 1");
}
@Test
public void testSubqueryBodyProjectedOrderby()
throws Exception
{
assertQuery("(SELECT orderkey, custkey FROM ORDERS) ORDER BY orderkey * -1");
}
@Test
public void testSubqueryBodyDoubleOrderby()
throws Exception
{
assertQuery("(SELECT orderkey, custkey FROM ORDERS ORDER BY custkey) ORDER BY orderkey");
}
@Test
public void testNodeRoster()
throws Exception
{
List<MaterializedTuple> result = computeActual("SELECT * FROM sys.node").getMaterializedTuples();
assertEquals(result.size(), getNodeCount());
}
@Test
public void testDual()
throws Exception
{
MaterializedResult result = computeActual("SELECT * FROM dual");
List<MaterializedTuple> tuples = result.getMaterializedTuples();
assertEquals(tuples.size(), 1);
}
@Test
public void testShowTables()
throws Exception
{
MaterializedResult result = computeActual("SHOW TABLES");
ImmutableSet<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME, TPCH_LINEITEM_NAME));
}
@Test
public void testShowTablesFrom()
throws Exception
{
MaterializedResult result = computeActual("SHOW TABLES FROM DEFAULT");
ImmutableSet<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME, TPCH_LINEITEM_NAME));
result = computeActual("SHOW TABLES FROM TPCH.DEFAULT");
tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME, TPCH_LINEITEM_NAME));
result = computeActual("SHOW TABLES FROM UNKNOWN");
tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of());
}
@Test
public void testShowTablesLike()
throws Exception
{
MaterializedResult result = computeActual("SHOW TABLES LIKE 'or%'");
ImmutableSet<String> tableNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), onlyColumnGetter()));
assertEquals(tableNames, ImmutableSet.of(TPCH_ORDERS_NAME));
}
@Test
public void testShowColumns()
throws Exception
{
MaterializedResult result = computeActual("SHOW COLUMNS FROM orders");
ImmutableSet<String> columnNames = ImmutableSet.copyOf(transform(result.getMaterializedTuples(), new Function<MaterializedTuple, String>()
{
@Override
public String apply(MaterializedTuple input)
{
assertEquals(input.getFieldCount(), 4);
return (String) input.getField(0);
}
}));
assertEquals(columnNames, ImmutableSet.of("orderkey", "custkey", "orderstatus", "totalprice", "orderdate", "orderpriority", "clerk", "shippriority", "comment"));
}
@Test
public void testShowFunctions()
throws Exception
{
MaterializedResult result = computeActual("SHOW FUNCTIONS");
ImmutableMultimap<String, MaterializedTuple> functions = Multimaps.index(result.getMaterializedTuples(), new Function<MaterializedTuple, String>()
{
@Override
public String apply(MaterializedTuple input)
{
assertEquals(input.getFieldCount(), 4);
return (String) input.getField(0);
}
});
assertTrue(functions.containsKey("avg"), "Expected function names " + functions + " to contain 'avg'");
assertEquals(functions.get("avg").asList().get(0).getField(3), "aggregate");
assertTrue(functions.containsKey("abs"), "Expected function names " + functions + " to contain 'abs'");
assertEquals(functions.get("abs").asList().get(0).getField(3), "scalar");
assertTrue(functions.containsKey("rand"), "Expected function names " + functions + " to contain 'rand'");
assertEquals(functions.get("rand").asList().get(0).getField(3), "scalar (non-deterministic)");
assertTrue(functions.containsKey("rank"), "Expected function names " + functions + " to contain 'rank'");
assertEquals(functions.get("rank").asList().get(0).getField(3), "window");
}
@Test
public void testNoFrom()
throws Exception
{
assertQuery("SELECT 1 + 2, 3 + 4", "SELECT 1 + 2, 3 + 4 FROM orders LIMIT 1");
}
@Test
public void testTopNByMultipleFields()
throws Exception
{
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey ASC LIMIT 10");
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey DESC LIMIT 10");
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey ASC LIMIT 10");
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey DESC LIMIT 10");
// now try with order by fields swapped
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey ASC LIMIT 10");
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey DESC LIMIT 10");
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey ASC LIMIT 10");
assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey DESC LIMIT 10");
}
@Test
public void testUnion()
throws Exception
{
assertQuery("SELECT orderkey FROM orders UNION SELECT custkey FROM orders");
}
@Test
public void testUnionDistinct()
throws Exception
{
assertQuery("SELECT orderkey FROM orders UNION DISTINCT SELECT custkey FROM orders");
}
@Test
public void testUnionAll()
throws Exception
{
assertQuery("SELECT orderkey FROM orders UNION ALL SELECT custkey FROM orders");
}
@Test
public void testChainedUnionsWithOrder()
throws Exception
{
assertQuery("SELECT orderkey FROM orders UNION (SELECT custkey FROM orders UNION SELECT linenumber FROM lineitem) UNION ALL SELECT orderkey FROM lineitem ORDER BY orderkey");
}
@Test
public void testSubqueryUnion()
throws Exception
{
assertQuery("SELECT * FROM (SELECT orderkey FROM orders UNION SELECT custkey FROM orders UNION SELECT orderkey FROM orders) ORDER BY orderkey LIMIT 1000");
}
@BeforeClass(alwaysRun = true)
public void setupDatabase()
throws Exception
{
Logging.initialize();
handle = DBI.open("jdbc:h2:mem:test" + System.nanoTime());
RecordSet ordersRecords = readTpchRecords(TPCH_ORDERS_METADATA);
handle.execute("CREATE TABLE orders (\n" +
" orderkey BIGINT PRIMARY KEY,\n" +
" custkey BIGINT NOT NULL,\n" +
" orderstatus CHAR(1) NOT NULL,\n" +
" totalprice DOUBLE NOT NULL,\n" +
" orderdate CHAR(10) NOT NULL,\n" +
" orderpriority CHAR(15) NOT NULL,\n" +
" clerk CHAR(15) NOT NULL,\n" +
" shippriority BIGINT NOT NULL,\n" +
" comment VARCHAR(79) NOT NULL\n" +
")");
insertRows(TPCH_ORDERS_METADATA, handle, ordersRecords);
RecordSet lineItemRecords = readTpchRecords(TPCH_LINEITEM_METADATA);
handle.execute("CREATE TABLE lineitem (\n" +
" orderkey BIGINT,\n" +
" partkey BIGINT NOT NULL,\n" +
" suppkey BIGINT NOT NULL,\n" +
" linenumber BIGINT,\n" +
" quantity BIGINT NOT NULL,\n" +
" extendedprice DOUBLE NOT NULL,\n" +
" discount DOUBLE NOT NULL,\n" +
" tax DOUBLE NOT NULL,\n" +
" returnflag CHAR(1) NOT NULL,\n" +
" linestatus CHAR(1) NOT NULL,\n" +
" shipdate CHAR(10) NOT NULL,\n" +
" commitdate CHAR(10) NOT NULL,\n" +
" receiptdate CHAR(10) NOT NULL,\n" +
" shipinstruct VARCHAR(25) NOT NULL,\n" +
" shipmode VARCHAR(10) NOT NULL,\n" +
" comment VARCHAR(44) NOT NULL,\n" +
" PRIMARY KEY (orderkey, linenumber)" +
")");
insertRows(TPCH_LINEITEM_METADATA, handle, lineItemRecords);
setUpQueryFramework(TpchMetadata.TPCH_CATALOG_NAME, TpchMetadata.TPCH_SCHEMA_NAME);
}
@AfterClass(alwaysRun = true)
public void cleanupDatabase()
throws Exception
{
tearDownQueryFramework();
handle.close();
}
protected abstract int getNodeCount();
protected abstract void setUpQueryFramework(String catalog, String schema)
throws Exception;
protected void tearDownQueryFramework()
throws Exception
{
}
protected abstract MaterializedResult computeActual(@Language("SQL") String sql);
protected void assertQuery(@Language("SQL") String sql)
throws Exception
{
assertQuery(sql, sql, false);
}
private void assertQueryOrdered(@Language("SQL") String sql)
throws Exception
{
assertQuery(sql, sql, true);
}
protected void assertQuery(@Language("SQL") String actual, @Language("SQL") String expected)
throws Exception
{
assertQuery(actual, expected, false);
}
private static final Logger log = Logger.get(AbstractTestQueries.class);
private void assertQuery(@Language("SQL") String actual, @Language("SQL") String expected, boolean ensureOrdering)
throws Exception
{
long start = System.nanoTime();
MaterializedResult actualResults = computeActual(actual);
log.info("FINISHED in %s", Duration.nanosSince(start));
MaterializedResult expectedResults = computeExpected(expected, actualResults.getTupleInfo());
if (ensureOrdering) {
assertEquals(actualResults.getMaterializedTuples(), expectedResults.getMaterializedTuples());
}
else {
assertEqualsIgnoreOrder(actualResults.getMaterializedTuples(), expectedResults.getMaterializedTuples());
}
}
public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected)
{
assertNotNull(actual, "actual is null");
assertNotNull(expected, "expected is null");
ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual);
ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected);
if (!actualSet.equals(expectedSet)) {
fail(format("not equal\nActual %s rows:\n %s\nExpected %s rows:\n %s\n",
actualSet.size(),
Joiner.on("\n ").join(Iterables.limit(actualSet, 100)),
expectedSet.size(),
Joiner.on("\n ").join(Iterables.limit(expectedSet, 100))));
}
}
private MaterializedResult computeExpected(@Language("SQL") final String sql, TupleInfo resultTupleInfo)
{
return new MaterializedResult(
handle.createQuery(sql)
.map(tupleMapper(resultTupleInfo))
.list(),
resultTupleInfo
);
}
private static ResultSetMapper<Tuple> tupleMapper(final TupleInfo tupleInfo)
{
return new ResultSetMapper<Tuple>()
{
@Override
public Tuple map(int index, ResultSet resultSet, StatementContext ctx)
throws SQLException
{
List<TupleInfo.Type> types = tupleInfo.getTypes();
int count = resultSet.getMetaData().getColumnCount();
checkArgument(types.size() == count, "tuple info does not match result");
TupleInfo.Builder builder = tupleInfo.builder();
for (int i = 1; i <= count; i++) {
TupleInfo.Type type = types.get(i - 1);
switch (type) {
case FIXED_INT_64:
long longValue = resultSet.getLong(i);
if (resultSet.wasNull()) {
builder.appendNull();
}
else {
builder.append(longValue);
}
break;
case DOUBLE:
double doubleValue = resultSet.getDouble(i);
if (resultSet.wasNull()) {
builder.appendNull();
}
else {
builder.append(doubleValue);
}
break;
case VARIABLE_BINARY:
String value = resultSet.getString(i);
if (resultSet.wasNull()) {
builder.appendNull();
}
else {
builder.append(Slices.wrappedBuffer(value.getBytes(UTF_8)));
}
break;
default:
throw new AssertionError("unhandled type: " + type);
}
}
return builder.build();
}
};
}
private static void insertRows(TableMetadata tableMetadata, Handle handle, RecordSet data)
{
String vars = Joiner.on(',').join(nCopies(tableMetadata.getColumns().size(), "?"));
String sql = format("INSERT INTO %s VALUES (%s)", tableMetadata.getTable().getTableName(), vars);
RecordCursor cursor = data.cursor();
while (true) {
// insert 1000 rows at a time
PreparedBatch batch = handle.prepareBatch(sql);
for (int row = 0; row < 1000; row++) {
if (!cursor.advanceNextPosition()) {
batch.execute();
return;
}
PreparedBatchPart part = batch.add();
for (int column = 0; column < tableMetadata.getColumns().size(); column++) {
ColumnMetadata columnMetadata = tableMetadata.getColumns().get(column);
switch (columnMetadata.getType()) {
case LONG:
part.bind(column, cursor.getLong(column));
break;
case DOUBLE:
part.bind(column, cursor.getDouble(column));
break;
case STRING:
part.bind(column, new String(cursor.getString(column), UTF_8));
break;
}
}
}
batch.execute();
}
}
private Function<MaterializedTuple, String> onlyColumnGetter()
{
return new Function<MaterializedTuple, String>()
{
@Override
public String apply(MaterializedTuple input)
{
assertEquals(input.getFieldCount(), 1);
return (String) input.getField(0);
}
};
}
}
|
Fix unit tests that should check for ordering
|
presto-main/src/test/java/com/facebook/presto/AbstractTestQueries.java
|
Fix unit tests that should check for ordering
|
<ide><path>resto-main/src/test/java/com/facebook/presto/AbstractTestQueries.java
<ide> public void testDistinctWithOrderBy()
<ide> throws Exception
<ide> {
<del> assertQuery("SELECT DISTINCT custkey FROM orders ORDER BY custkey LIMIT 10");
<add> assertQueryOrdered("SELECT DISTINCT custkey FROM orders ORDER BY custkey LIMIT 10");
<ide> }
<ide>
<ide> @Test(expectedExceptions = Exception.class, expectedExceptionsMessageRegExp = "For SELECT DISTINCT, ORDER BY expressions must appear in select list")
<ide> public void testDistinctWithOrderByNotInSelect()
<ide> throws Exception
<ide> {
<del> assertQuery("SELECT DISTINCT custkey FROM orders ORDER BY orderkey LIMIT 10");
<add> assertQueryOrdered("SELECT DISTINCT custkey FROM orders ORDER BY orderkey LIMIT 10");
<ide> }
<ide>
<ide> @Test
<ide> public void testOrderByMultipleFields()
<ide> throws Exception
<ide> {
<del> assertQuery("SELECT orderkey, orderstatus FROM orders ORDER BY custkey DESC, orderstatus");
<add> assertQueryOrdered("SELECT custkey, orderstatus FROM orders ORDER BY custkey DESC, orderstatus");
<ide> }
<ide>
<ide> @Test
<ide> public void testCaseInsensitiveOutputAliasInOrderBy()
<ide> throws Exception
<ide> {
<del> assertQuery("SELECT orderkey X FROM orders ORDER BY x");
<add> assertQueryOrdered("SELECT orderkey X FROM orders ORDER BY x");
<ide> }
<ide>
<ide> @Test
<ide> public void testSubqueryBodyOrderLimit()
<ide> throws Exception
<ide> {
<del> assertQuery("(SELECT orderkey AS a, custkey AS b FROM ORDERS) ORDER BY a LIMIT 1");
<add> assertQueryOrdered("(SELECT orderkey AS a, custkey AS b FROM ORDERS) ORDER BY a LIMIT 1");
<ide> }
<ide>
<ide> @Test
<ide> public void testSubqueryBodyProjectedOrderby()
<ide> throws Exception
<ide> {
<del> assertQuery("(SELECT orderkey, custkey FROM ORDERS) ORDER BY orderkey * -1");
<add> assertQueryOrdered("(SELECT orderkey, custkey FROM ORDERS) ORDER BY orderkey * -1");
<ide> }
<ide>
<ide> @Test
<ide> public void testSubqueryBodyDoubleOrderby()
<ide> throws Exception
<ide> {
<del> assertQuery("(SELECT orderkey, custkey FROM ORDERS ORDER BY custkey) ORDER BY orderkey");
<add> assertQueryOrdered("(SELECT orderkey, custkey FROM ORDERS ORDER BY custkey) ORDER BY orderkey");
<ide> }
<ide>
<ide> @Test
<ide> public void testTopNByMultipleFields()
<ide> throws Exception
<ide> {
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey ASC LIMIT 10");
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey DESC LIMIT 10");
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey ASC LIMIT 10");
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey DESC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey ASC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey ASC, custkey DESC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey ASC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY orderkey DESC, custkey DESC LIMIT 10");
<ide>
<ide> // now try with order by fields swapped
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey ASC LIMIT 10");
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey DESC LIMIT 10");
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey ASC LIMIT 10");
<del> assertQuery("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey DESC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey ASC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey ASC, orderkey DESC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey ASC LIMIT 10");
<add> assertQueryOrdered("SELECT orderkey, custkey, orderstatus FROM orders ORDER BY custkey DESC, orderkey DESC LIMIT 10");
<ide> }
<ide>
<ide> @Test
<ide> public void testChainedUnionsWithOrder()
<ide> throws Exception
<ide> {
<del> assertQuery("SELECT orderkey FROM orders UNION (SELECT custkey FROM orders UNION SELECT linenumber FROM lineitem) UNION ALL SELECT orderkey FROM lineitem ORDER BY orderkey");
<add> assertQueryOrdered("SELECT orderkey FROM orders UNION (SELECT custkey FROM orders UNION SELECT linenumber FROM lineitem) UNION ALL SELECT orderkey FROM lineitem ORDER BY orderkey");
<ide> }
<ide>
<ide> @Test
<ide> public void testSubqueryUnion()
<ide> throws Exception
<ide> {
<del> assertQuery("SELECT * FROM (SELECT orderkey FROM orders UNION SELECT custkey FROM orders UNION SELECT orderkey FROM orders) ORDER BY orderkey LIMIT 1000");
<add> assertQueryOrdered("SELECT * FROM (SELECT orderkey FROM orders UNION SELECT custkey FROM orders UNION SELECT orderkey FROM orders) ORDER BY orderkey LIMIT 1000");
<ide> }
<ide>
<ide> @BeforeClass(alwaysRun = true)
|
|
Java
|
mit
|
ad0355cf65c2f1ad0ada40aa60b51c0615bc8ebb
| 0 |
GlowstoneMC/GlowstonePlusPlus,Postremus/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,BlazePowered/Blaze-Server,jimmikaelkael/GlowstonePlusPlus,Postremus/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,keke142/GlowstonePlusPlus,jimmikaelkael/GlowstonePlusPlus,GreenBeard/GlowstonePlusPlus,GreenBeard/GlowstonePlusPlus,keke142/GlowstonePlusPlus,GreenBeard/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,keke142/GlowstonePlusPlus,BlazePowered/Blaze-Server,GlowstoneMC/GlowstonePlusPlus,jimmikaelkael/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,keke142/GlowstonePlusPlus,BlazePowered/Blaze-Server,BlazePowered/Blaze-Server,Postremus/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,jimmikaelkael/GlowstonePlusPlus,GreenBeard/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,Postremus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,LukBukkit/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus
|
package net.glowstone.util;
import net.glowstone.GlowServer;
import org.apache.commons.lang.Validate;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.util.FileUtil;
import org.yaml.snakeyaml.error.YAMLException;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
/**
* Utilities for handling the server configuration files.
*/
public final class ServerConfig {
/**
* The directory configurations are stored in.
*/
private final File configDir;
/**
* The main configuration file.
*/
private final File configFile;
/**
* The actual configuration data.
*/
private final YamlConfiguration config = new YamlConfiguration();
/**
* Extra configuration files (help, permissions, commands).
*/
private final Map<String, YamlConfiguration> extraConfig = new HashMap<>();
/**
* Parameters with which the server is ran.
*/
private final Map<Key, Object> parameters;
/**
* Initialize a new ServerConfig and associated settings.
* @param configDir The config directory, or null for default.
* @param configFile The config file, or null for default.
* @param parameters The command-line parameters used as overrides.
*/
public ServerConfig(File configDir, File configFile, Map<Key, Object> parameters) {
Validate.notNull(configDir);
Validate.notNull(configFile);
Validate.notNull(parameters);
this.configDir = configDir;
this.configFile = configFile;
this.parameters = parameters;
config.options().indent(4).copyHeader(true).header(
"glowstone.yml is the main configuration file for a Glowstone server\n" +
"It contains everything from server.properties and bukkit.yml in a\n" +
"normal CraftBukkit installation.\n\n" +
"For help, join us on IRC: #glowstone @ esper.net");
}
////////////////////////////////////////////////////////////////////////////
// Modification
/**
* Save the configuration back to file.
*/
public void save() {
try {
config.save(configFile);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to write config: " + configFile, e);
}
}
/**
* Change a configuration value at runtime.
* @see ServerConfig#save()
* @param key the config key to write the value to
* @param value value to write to config key
*/
public void set(Key key, Object value) {
config.set(key.path, value);
}
////////////////////////////////////////////////////////////////////////////
// Value getters
public String getString(Key key) {
if (parameters.containsKey(key)) {
return parameters.get(key).toString();
}
return config.getString(key.path, key.def.toString());
}
public int getInt(Key key) {
if (parameters.containsKey(key)) {
return (Integer) parameters.get(key);
}
return config.getInt(key.path, (Integer) key.def);
}
public boolean getBoolean(Key key) {
if (parameters.containsKey(key)) {
return (Boolean) parameters.get(key);
}
return config.getBoolean(key.path, (Boolean) key.def);
}
////////////////////////////////////////////////////////////////////////////
// Fancy stuff
public ConfigurationSection getConfigFile(Key key) {
String filename = getString(key);
if (extraConfig.containsKey(filename)) {
return extraConfig.get(filename);
}
final YamlConfiguration conf = new YamlConfiguration();
final File file = getFile(filename), migrateFrom = new File(key.def.toString());
// create file if it doesn't exist
if (!file.exists()) {
if (migrateFrom.exists()) {
FileUtil.copy(migrateFrom, file);
} else {
copyDefaults(key.def.toString(), file);
}
}
// read in config
try {
conf.load(file);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to read config: " + file, e);
} catch (InvalidConfigurationException e) {
report(file, e);
}
extraConfig.put(filename, conf);
return conf;
}
public ConfigurationSection getWorlds() {
return config.getConfigurationSection("worlds");
}
public File getDirectory() {
return configDir;
}
public File getFile(String filename) {
return new File(configDir, filename);
}
////////////////////////////////////////////////////////////////////////////
// Load and internals
public void load() {
// load extra config files again next time they're needed
extraConfig.clear();
// create default file if needed
if (!configFile.exists()) {
// create config directory
if (!configDir.isDirectory() && !configDir.mkdirs()) {
GlowServer.logger.severe("Cannot create directory: " + configDir);
return;
}
// load default config
for (Key key : Key.values()) {
config.set(key.path, key.def);
}
// attempt to migrate
if (migrate()) {
GlowServer.logger.info("Migrated configuration from previous installation");
}
// save config, including any new defaults
try {
config.save(configFile);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to write config: " + configFile, e);
return;
}
GlowServer.logger.info("Created default config: " + configFile);
} else {
// load config
try {
config.load(configFile);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to read config: " + configFile, e);
} catch (InvalidConfigurationException e) {
report(configFile, e);
}
}
}
private void copyDefaults(String source, File dest) {
final URL resource = getClass().getClassLoader().getResource("defaults/" + source);
if (resource == null) {
GlowServer.logger.warning("Could not find default " + source + " on classpath");
return;
}
try (final InputStream in = resource.openStream();
final OutputStream out = new FileOutputStream(dest)) {
final byte[] buf = new byte[2048];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
GlowServer.logger.log(Level.WARNING, "Could not save default config: " + dest, e);
return;
}
GlowServer.logger.info("Created default config: " + dest);
}
private void report(File file, InvalidConfigurationException e) {
if (e.getCause() instanceof YAMLException) {
GlowServer.logger.severe("Config file " + file + " isn't valid! " + e.getCause());
} else if ((e.getCause() == null) || (e.getCause() instanceof ClassCastException)) {
GlowServer.logger.severe("Config file " + file + " isn't valid!");
} else {
GlowServer.logger.log(Level.SEVERE, "Cannot load " + file + ": " + e.getCause().getClass(), e);
}
}
private boolean migrate() {
boolean migrateStatus = false;
final File bukkitYml = new File("bukkit.yml");
if (bukkitYml.exists()) {
YamlConfiguration bukkit = new YamlConfiguration();
try {
bukkit.load(bukkitYml);
} catch (InvalidConfigurationException e) {
report(bukkitYml, e);
} catch (IOException e) {
GlowServer.logger.log(Level.WARNING, "Could not migrate from " + bukkitYml, e);
}
for (Key key : Key.values()) {
if (key.migrate == Migrate.BUKKIT && bukkit.contains(key.migratePath)) {
config.set(key.path, bukkit.get(key.migratePath));
migrateStatus = true;
}
}
config.set("aliases", bukkit.get("aliases"));
config.set("worlds", bukkit.get("worlds"));
}
final File serverProps = new File("server.properties");
if (serverProps.exists()) {
Properties props = new Properties();
try {
props.load(new FileInputStream(serverProps));
} catch (IOException e) {
GlowServer.logger.log(Level.WARNING, "Could not migrate from " + serverProps, e);
}
for (Key key : Key.values()) {
if (key.migrate == Migrate.PROPS && props.containsKey(key.migratePath)) {
String value = props.getProperty(key.migratePath);
if (key.def instanceof Integer) {
try {
config.set(key.path, Integer.parseInt(value));
} catch (NumberFormatException e) {
GlowServer.logger.log(Level.WARNING, "Could not migrate " + key.migratePath + " from " + serverProps, e);
continue;
}
} else if (key.def instanceof Boolean) {
config.set(key.path, Boolean.parseBoolean(value));
} else {
config.set(key.path, value);
}
migrateStatus = true;
}
}
}
return migrateStatus;
}
/**
* An enum containing configuration keys used by the server.
*/
public static enum Key {
// server
SERVER_IP("server.ip", "", Migrate.PROPS, "server-ip"),
SERVER_PORT("server.port", 25565, Migrate.PROPS, "server-port"),
SERVER_NAME("server.name", "Glowstone Server", Migrate.PROPS, "server-name"),
LOG_FILE("server.log-file", "logs/log-%D.txt"),
ONLINE_MODE("server.online-mode", true, Migrate.PROPS, "online-mode"),
MAX_PLAYERS("server.max-players", 20, Migrate.PROPS, "max-players"),
WHITELIST("server.whitelisted", false, Migrate.PROPS, "white-list"),
MOTD("server.motd", "Glowstone Server", Migrate.PROPS, "motd"),
SHUTDOWN_MESSAGE("server.shutdown-message", "Server shutting down.", Migrate.BUKKIT, "settings.shutdown-message"),
USE_JLINE("server.use-jline", true),
// folders
PLUGIN_FOLDER("folders.plugins", "plugins"),
UPDATE_FOLDER("folders.update", "update", Migrate.BUKKIT, "settings.update-folder"),
WORLD_FOLDER("folders.worlds", "worlds", Migrate.BUKKIT, "settings.world-container"),
// files
PERMISSIONS_FILE("files.permissions", "permissions.yml", Migrate.BUKKIT, "settings.permissions-file"),
COMMANDS_FILE("files.commands", "commands.yml"),
HELP_FILE("files.help", "help.yml"),
// advanced
CONNECTION_THROTTLE("advanced.connection-throttle", 4000, Migrate.BUKKIT, "settings.connection-throttle"),
//PING_PACKET_LIMIT("advanced.ping-packet-limit", 100, Migrate.BUKKIT, "settings.ping-packet-limit"),
PLAYER_IDLE_TIMEOUT("advanced.idle-timeout", 0, Migrate.PROPS, "player-idle-timeout"),
WARN_ON_OVERLOAD("advanced.warn-on-overload", true, Migrate.BUKKIT, "settings.warn-on-overload"),
EXACT_LOGIN_LOCATION("advanced.exact-login-location", false, Migrate.BUKKIT, "settings.use-exact-login-location"),
PLUGIN_PROFILING("advanced.plugin-profiling", false, Migrate.BUKKIT, "settings.plugin-profiling"),
WARNING_STATE("advanced.deprecated-verbose", "false", Migrate.BUKKIT, "settings.deprecated-verbose"),
COMPRESSION_THRESHOLD("advanced.compression-threshold", 256, Migrate.PROPS, "network-compression-threshold"),
PROXY_SUPPORT("advanced.proxy-support", false),
// query rcon etc
QUERY_ENABLED("extras.query-enabled", false, Migrate.PROPS, "enable-query"),
QUERY_PORT("extras.query-port", 25614, Migrate.PROPS, "query.port"),
QUERY_PLUGINS("extras.query-plugins", true, Migrate.BUKKIT, "settings.query-plugins"),
RCON_ENABLED("extras.rcon-enabled", false, Migrate.PROPS, "enable-rcon"),
RCON_PASSWORD("extras.rcon-password", "glowstone", Migrate.PROPS, "rcon.password"),
RCON_PORT("extras.rcon-port", 25575, Migrate.PROPS, "rcon.port"),
RCON_COLORS("extras.rcon-colors", true),
// level props
LEVEL_NAME("world.name", "world", Migrate.PROPS, "level-name"),
LEVEL_SEED("world.seed", "", Migrate.PROPS, "level-seed"),
LEVEL_TYPE("world.level-type", "DEFAULT", Migrate.PROPS, "level-type"),
SPAWN_RADIUS("world.spawn-radius", 16, Migrate.PROPS, "spawn-protection"),
VIEW_DISTANCE("world.view-distance", 8, Migrate.PROPS, "view-distance"),
GENERATE_STRUCTURES("world.gen-structures", true, Migrate.PROPS, "generate-structures"),
GENERATOR_SETTINGS("world.gen-settings", "", Migrate.PROPS, "generator-settings"),
ALLOW_NETHER("world.allow-nether", true, Migrate.PROPS, "allow-nether"),
ALLOW_END("world.allow-end", true, Migrate.BUKKIT, "settings.allow-end"),
PERSIST_SPAWN("world.keep-spawn-loaded", true),
// game props
GAMEMODE("game.gamemode", "SURVIVAL", Migrate.PROPS, "gamemode"),
FORCE_GAMEMODE("game.gamemode-force", "false", Migrate.PROPS, "force-gamemode"),
DIFFICULTY("game.difficulty", "NORMAL", Migrate.PROPS, "difficulty"),
HARDCORE("game.hardcore", false, Migrate.PROPS, "hardcore"),
PVP_ENABLED("game.pvp", true, Migrate.PROPS, "pvp"),
MAX_BUILD_HEIGHT("game.max-build-height", 256, Migrate.PROPS, "max-build-height"),
ANNOUNCE_ACHIEVEMENTS("game.announce-achievements", true, Migrate.PROPS, "announce-player-achievements"),
// server.properties keys
ALLOW_FLIGHT("game.allow-flight", false, Migrate.PROPS, "allow-flight"),
ENABLE_COMMAND_BLOCK("game.command-blocks", false, Migrate.PROPS, "enable-command-block"),
//OP_PERMISSION_LEVEL(null, Migrate.PROPS, "op-permission-level"),
RESOURCE_PACK("game.resource-pack", "", Migrate.PROPS, "resource-pack"),
RESOURCE_PACK_HASH("game.resource-pack-hash", "", Migrate.PROPS, "resource-pack-hash"),
SNOOPER_ENABLED("server.snooper-enabled", false, Migrate.PROPS, "snooper-enabled"),
// critters
SPAWN_MONSTERS("creatures.enable.monsters", true, Migrate.PROPS, "spawn-monsters"),
SPAWN_ANIMALS("creatures.enable.animals", true, Migrate.PROPS, "spawn-animals"),
SPAWN_NPCS("creatures.enable.npcs", true, Migrate.PROPS, "spawn-npcs"),
MONSTER_LIMIT("creatures.limit.monsters", 70, Migrate.BUKKIT, "spawn-limits.monsters"),
ANIMAL_LIMIT("creatures.limit.animals", 15, Migrate.BUKKIT, "spawn-limits.animals"),
WATER_ANIMAL_LIMIT("creatures.limit.water", 5, Migrate.BUKKIT, "spawn-limits.water-animals"),
AMBIENT_LIMIT("creatures.limit.ambient", 15, Migrate.BUKKIT, "spawn-limits.ambient"),
MONSTER_TICKS("creatures.ticks.monsters", 1, Migrate.BUKKIT, "ticks-per.monster-spawns"),
ANIMAL_TICKS("creatures.ticks.animal", 400, Migrate.BUKKIT, "ticks-per.animal-spawns"),
// database
DB_DRIVER("database.driver", "org.sqlite.JDBC", Migrate.BUKKIT, "database.driver"),
DB_URL("database.url", "jdbc:sqlite:config/database.db", Migrate.BUKKIT, "database.url"),
DB_USERNAME("database.username", "glowstone", Migrate.BUKKIT, "database.username"),
DB_PASSWORD("database.password", "nether", Migrate.BUKKIT, "database.password"),
DB_ISOLATION("database.isolation", "SERIALIZABLE", Migrate.BUKKIT, "database.isolation");
private final String path;
private final Object def;
private final Migrate migrate;
private final String migratePath;
private Key(String path, Object def) {
this(path, def, null, null);
}
private Key(String path, Object def, Migrate migrate, String migratePath) {
this.path = path;
this.def = def;
this.migrate = migrate;
this.migratePath = migratePath;
}
@Override
public String toString() {
return name() + "(" + path + ", " + def + ")";
}
}
private static enum Migrate {
BUKKIT, PROPS
}
}
|
src/main/java/net/glowstone/util/ServerConfig.java
|
package net.glowstone.util;
import net.glowstone.GlowServer;
import org.apache.commons.lang.Validate;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.util.FileUtil;
import org.yaml.snakeyaml.error.YAMLException;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
/**
* Utilities for handling the server configuration files.
*/
public final class ServerConfig {
/**
* The directory configurations are stored in.
*/
private final File configDir;
/**
* The main configuration file.
*/
private final File configFile;
/**
* The actual configuration data.
*/
private final YamlConfiguration config = new YamlConfiguration();
/**
* Extra configuration files (help, permissions, commands).
*/
private final Map<String, YamlConfiguration> extraConfig = new HashMap<>();
/**
* Parameters with which the server is ran.
*/
private final Map<Key, Object> parameters;
/**
* Initialize a new ServerConfig and associated settings.
* @param configDir The config directory, or null for default.
* @param configFile The config file, or null for default.
* @param parameters The command-line parameters used as overrides.
*/
public ServerConfig(File configDir, File configFile, Map<Key, Object> parameters) {
Validate.notNull(configDir);
Validate.notNull(configFile);
Validate.notNull(parameters);
this.configDir = configDir;
this.configFile = configFile;
this.parameters = parameters;
config.options().indent(4).copyHeader(true).header(
"glowstone.yml is the main configuration file for a Glowstone server\n" +
"It contains everything from server.properties and bukkit.yml in a\n" +
"normal CraftBukkit installation.\n\n" +
"For help, join us on IRC: #glowstone @ esper.net");
}
////////////////////////////////////////////////////////////////////////////
// Modification
/**
* Save the configuration back to file.
*/
public void save() {
try {
config.save(configFile);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to write config: " + configFile, e);
}
}
/**
* Change a configuration value at runtime.
* @see ServerConfig#save()
* @param key the config key to write the value to
* @param value value to write to config key
*/
public void set(Key key, Object value) {
config.set(key.path, value);
}
////////////////////////////////////////////////////////////////////////////
// Value getters
public String getString(Key key) {
if (parameters.containsKey(key)) {
return parameters.get(key).toString();
}
return config.getString(key.path, key.def.toString());
}
public int getInt(Key key) {
if (parameters.containsKey(key)) {
return (Integer) parameters.get(key);
}
return config.getInt(key.path, (Integer) key.def);
}
public boolean getBoolean(Key key) {
if (parameters.containsKey(key)) {
return (Boolean) parameters.get(key);
}
return config.getBoolean(key.path, (Boolean) key.def);
}
////////////////////////////////////////////////////////////////////////////
// Fancy stuff
public ConfigurationSection getConfigFile(Key key) {
String filename = getString(key);
if (extraConfig.containsKey(filename)) {
return extraConfig.get(filename);
}
final YamlConfiguration conf = new YamlConfiguration();
final File file = getFile(filename), migrateFrom = new File(key.def.toString());
// create file if it doesn't exist
if (!file.exists()) {
if (migrateFrom.exists()) {
FileUtil.copy(migrateFrom, file);
} else {
copyDefaults(key.def.toString(), file);
}
}
// read in config
try {
conf.load(file);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to read config: " + file, e);
} catch (InvalidConfigurationException e) {
report(file, e);
}
extraConfig.put(filename, conf);
return conf;
}
public ConfigurationSection getWorlds() {
return config.getConfigurationSection("worlds");
}
public File getDirectory() {
return configDir;
}
public File getFile(String filename) {
return new File(configDir, filename);
}
////////////////////////////////////////////////////////////////////////////
// Load and internals
public void load() {
// load extra config files again next time they're needed
extraConfig.clear();
// create default file if needed
if (!configFile.exists()) {
// create config directory
if (!configDir.isDirectory() && !configDir.mkdirs()) {
GlowServer.logger.severe("Cannot create directory: " + configDir);
return;
}
// load default config
for (Key key : Key.values()) {
config.set(key.path, key.def);
}
// attempt to migrate
if(migrate()) {
GlowServer.logger.info("Migrated configuration from previous installation");
}
// save config, including any new defaults
try {
config.save(configFile);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to write config: " + configFile, e);
return;
}
GlowServer.logger.info("Created default config: " + configFile);
} else {
// load config
try {
config.load(configFile);
} catch (IOException e) {
GlowServer.logger.log(Level.SEVERE, "Failed to read config: " + configFile, e);
} catch (InvalidConfigurationException e) {
report(configFile, e);
}
}
}
private void copyDefaults(String source, File dest) {
final URL resource = getClass().getClassLoader().getResource("defaults/" + source);
if (resource == null) {
GlowServer.logger.warning("Could not find default " + source + " on classpath");
return;
}
try (final InputStream in = resource.openStream();
final OutputStream out = new FileOutputStream(dest)) {
final byte[] buf = new byte[2048];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
GlowServer.logger.log(Level.WARNING, "Could not save default config: " + dest, e);
return;
}
GlowServer.logger.info("Created default config: " + dest);
}
private void report(File file, InvalidConfigurationException e) {
if (e.getCause() instanceof YAMLException) {
GlowServer.logger.severe("Config file " + file + " isn't valid! " + e.getCause());
} else if ((e.getCause() == null) || (e.getCause() instanceof ClassCastException)) {
GlowServer.logger.severe("Config file " + file + " isn't valid!");
} else {
GlowServer.logger.log(Level.SEVERE, "Cannot load " + file + ": " + e.getCause().getClass(), e);
}
}
private boolean migrate() {
boolean migrateStatus = false;
final File bukkitYml = new File("bukkit.yml");
if (bukkitYml.exists()) {
YamlConfiguration bukkit = new YamlConfiguration();
try {
bukkit.load(bukkitYml);
} catch (InvalidConfigurationException e) {
report(bukkitYml, e);
} catch (IOException e) {
GlowServer.logger.log(Level.WARNING, "Could not migrate from " + bukkitYml, e);
}
for (Key key : Key.values()) {
if (key.migrate == Migrate.BUKKIT && bukkit.contains(key.migratePath)) {
config.set(key.path, bukkit.get(key.migratePath));
migrateStatus = true;
}
}
config.set("aliases", bukkit.get("aliases"));
config.set("worlds", bukkit.get("worlds"));
}
final File serverProps = new File("server.properties");
if (serverProps.exists()) {
Properties props = new Properties();
try {
props.load(new FileInputStream(serverProps));
} catch (IOException e) {
GlowServer.logger.log(Level.WARNING, "Could not migrate from " + serverProps, e);
}
for (Key key : Key.values()) {
if (key.migrate == Migrate.PROPS && props.containsKey(key.migratePath)) {
String value = props.getProperty(key.migratePath);
if (key.def instanceof Integer) {
try {
config.set(key.path, Integer.parseInt(value));
} catch (NumberFormatException e) {
GlowServer.logger.log(Level.WARNING, "Could not migrate " + key.migratePath + " from " + serverProps, e);
continue;
}
} else if (key.def instanceof Boolean) {
config.set(key.path, Boolean.parseBoolean(value));
} else {
config.set(key.path, value);
}
migrateStatus = true;
}
}
}
return migrateStatus;
}
/**
* An enum containing configuration keys used by the server.
*/
public static enum Key {
// server
SERVER_IP("server.ip", "", Migrate.PROPS, "server-ip"),
SERVER_PORT("server.port", 25565, Migrate.PROPS, "server-port"),
SERVER_NAME("server.name", "Glowstone Server", Migrate.PROPS, "server-name"),
LOG_FILE("server.log-file", "logs/log-%D.txt"),
ONLINE_MODE("server.online-mode", true, Migrate.PROPS, "online-mode"),
MAX_PLAYERS("server.max-players", 20, Migrate.PROPS, "max-players"),
WHITELIST("server.whitelisted", false, Migrate.PROPS, "white-list"),
MOTD("server.motd", "Glowstone Server", Migrate.PROPS, "motd"),
SHUTDOWN_MESSAGE("server.shutdown-message", "Server shutting down.", Migrate.BUKKIT, "settings.shutdown-message"),
USE_JLINE("server.use-jline", true),
// folders
PLUGIN_FOLDER("folders.plugins", "plugins"),
UPDATE_FOLDER("folders.update", "update", Migrate.BUKKIT, "settings.update-folder"),
WORLD_FOLDER("folders.worlds", "worlds", Migrate.BUKKIT, "settings.world-container"),
// files
PERMISSIONS_FILE("files.permissions", "permissions.yml", Migrate.BUKKIT, "settings.permissions-file"),
COMMANDS_FILE("files.commands", "commands.yml"),
HELP_FILE("files.help", "help.yml"),
// advanced
CONNECTION_THROTTLE("advanced.connection-throttle", 4000, Migrate.BUKKIT, "settings.connection-throttle"),
//PING_PACKET_LIMIT("advanced.ping-packet-limit", 100, Migrate.BUKKIT, "settings.ping-packet-limit"),
PLAYER_IDLE_TIMEOUT("advanced.idle-timeout", 0, Migrate.PROPS, "player-idle-timeout"),
WARN_ON_OVERLOAD("advanced.warn-on-overload", true, Migrate.BUKKIT, "settings.warn-on-overload"),
EXACT_LOGIN_LOCATION("advanced.exact-login-location", false, Migrate.BUKKIT, "settings.use-exact-login-location"),
PLUGIN_PROFILING("advanced.plugin-profiling", false, Migrate.BUKKIT, "settings.plugin-profiling"),
WARNING_STATE("advanced.deprecated-verbose", "false", Migrate.BUKKIT, "settings.deprecated-verbose"),
COMPRESSION_THRESHOLD("advanced.compression-threshold", 256, Migrate.PROPS, "network-compression-threshold"),
PROXY_SUPPORT("advanced.proxy-support", false),
// query rcon etc
QUERY_ENABLED("extras.query-enabled", false, Migrate.PROPS, "enable-query"),
QUERY_PORT("extras.query-port", 25614, Migrate.PROPS, "query.port"),
QUERY_PLUGINS("extras.query-plugins", true, Migrate.BUKKIT, "settings.query-plugins"),
RCON_ENABLED("extras.rcon-enabled", false, Migrate.PROPS, "enable-rcon"),
RCON_PASSWORD("extras.rcon-password", "glowstone", Migrate.PROPS, "rcon.password"),
RCON_PORT("extras.rcon-port", 25575, Migrate.PROPS, "rcon.port"),
RCON_COLORS("extras.rcon-colors", true),
// level props
LEVEL_NAME("world.name", "world", Migrate.PROPS, "level-name"),
LEVEL_SEED("world.seed", "", Migrate.PROPS, "level-seed"),
LEVEL_TYPE("world.level-type", "DEFAULT", Migrate.PROPS, "level-type"),
SPAWN_RADIUS("world.spawn-radius", 16, Migrate.PROPS, "spawn-protection"),
VIEW_DISTANCE("world.view-distance", 8, Migrate.PROPS, "view-distance"),
GENERATE_STRUCTURES("world.gen-structures", true, Migrate.PROPS, "generate-structures"),
GENERATOR_SETTINGS("world.gen-settings", "", Migrate.PROPS, "generator-settings"),
ALLOW_NETHER("world.allow-nether", true, Migrate.PROPS, "allow-nether"),
ALLOW_END("world.allow-end", true, Migrate.BUKKIT, "settings.allow-end"),
PERSIST_SPAWN("world.keep-spawn-loaded", true),
// game props
GAMEMODE("game.gamemode", "SURVIVAL", Migrate.PROPS, "gamemode"),
FORCE_GAMEMODE("game.gamemode-force", "false", Migrate.PROPS, "force-gamemode"),
DIFFICULTY("game.difficulty", "NORMAL", Migrate.PROPS, "difficulty"),
HARDCORE("game.hardcore", false, Migrate.PROPS, "hardcore"),
PVP_ENABLED("game.pvp", true, Migrate.PROPS, "pvp"),
MAX_BUILD_HEIGHT("game.max-build-height", 256, Migrate.PROPS, "max-build-height"),
ANNOUNCE_ACHIEVEMENTS("game.announce-achievements", true, Migrate.PROPS, "announce-player-achievements"),
// server.properties keys
ALLOW_FLIGHT("game.allow-flight", false, Migrate.PROPS, "allow-flight"),
ENABLE_COMMAND_BLOCK("game.command-blocks", false, Migrate.PROPS, "enable-command-block"),
//OP_PERMISSION_LEVEL(null, Migrate.PROPS, "op-permission-level"),
RESOURCE_PACK("game.resource-pack", "", Migrate.PROPS, "resource-pack"),
RESOURCE_PACK_HASH("game.resource-pack-hash", "", Migrate.PROPS, "resource-pack-hash"),
SNOOPER_ENABLED("server.snooper-enabled", false, Migrate.PROPS, "snooper-enabled"),
// critters
SPAWN_MONSTERS("creatures.enable.monsters", true, Migrate.PROPS, "spawn-monsters"),
SPAWN_ANIMALS("creatures.enable.animals", true, Migrate.PROPS, "spawn-animals"),
SPAWN_NPCS("creatures.enable.npcs", true, Migrate.PROPS, "spawn-npcs"),
MONSTER_LIMIT("creatures.limit.monsters", 70, Migrate.BUKKIT, "spawn-limits.monsters"),
ANIMAL_LIMIT("creatures.limit.animals", 15, Migrate.BUKKIT, "spawn-limits.animals"),
WATER_ANIMAL_LIMIT("creatures.limit.water", 5, Migrate.BUKKIT, "spawn-limits.water-animals"),
AMBIENT_LIMIT("creatures.limit.ambient", 15, Migrate.BUKKIT, "spawn-limits.ambient"),
MONSTER_TICKS("creatures.ticks.monsters", 1, Migrate.BUKKIT, "ticks-per.monster-spawns"),
ANIMAL_TICKS("creatures.ticks.animal", 400, Migrate.BUKKIT, "ticks-per.animal-spawns"),
// database
DB_DRIVER("database.driver", "org.sqlite.JDBC", Migrate.BUKKIT, "database.driver"),
DB_URL("database.url", "jdbc:sqlite:config/database.db", Migrate.BUKKIT, "database.url"),
DB_USERNAME("database.username", "glowstone", Migrate.BUKKIT, "database.username"),
DB_PASSWORD("database.password", "nether", Migrate.BUKKIT, "database.password"),
DB_ISOLATION("database.isolation", "SERIALIZABLE", Migrate.BUKKIT, "database.isolation");
private final String path;
private final Object def;
private final Migrate migrate;
private final String migratePath;
private Key(String path, Object def) {
this(path, def, null, null);
}
private Key(String path, Object def, Migrate migrate, String migratePath) {
this.path = path;
this.def = def;
this.migrate = migrate;
this.migratePath = migratePath;
}
@Override
public String toString() {
return name() + "(" + path + ", " + def + ")";
}
}
private static enum Migrate {
BUKKIT, PROPS
}
}
|
formatting
|
src/main/java/net/glowstone/util/ServerConfig.java
|
formatting
|
<ide><path>rc/main/java/net/glowstone/util/ServerConfig.java
<ide> }
<ide>
<ide> // attempt to migrate
<del> if(migrate()) {
<add> if (migrate()) {
<ide> GlowServer.logger.info("Migrated configuration from previous installation");
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
96df59750714a4a6a3ee523c2b009465fec380bc
| 0 |
andsel/moquette,andsel/moquette,andsel/moquette,windbender/moquette,andsel/moquette,windbender/moquette,windbender/moquette,windbender/moquette
|
package io.moquette.interception.messages;
/**
* An interface that sets the root of the interceptor messages type hierarchy.
*
* @author lbarrios
*
*/
public interface InterceptMessage {
}
|
broker/src/main/java/io/moquette/interception/messages/InterceptMessage.java
|
package io.moquette.interception.messages;
/**
* An interface that sets the root of the interceptor messages type hierarchy.
* @author lbarrios
*
*/
public interface InterceptMessage {
}
|
broker/InterceptMessage: code formatter used
|
broker/src/main/java/io/moquette/interception/messages/InterceptMessage.java
|
broker/InterceptMessage: code formatter used
|
<ide><path>roker/src/main/java/io/moquette/interception/messages/InterceptMessage.java
<add>
<ide> package io.moquette.interception.messages;
<ide>
<ide> /**
<ide> * An interface that sets the root of the interceptor messages type hierarchy.
<add> *
<ide> * @author lbarrios
<ide> *
<ide> */
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/system/java/org/apache/hadoop/mapred/TestJobCacheDirectoriesCleanUp.java' did not match any file(s) known to git
|
93e887e94df5779be1b88b3e426d37b7d96ae03f
| 1 |
aseldawy/spatialhadoop,ShortMap/ShortMap,ShortMap/ShortMap,aseldawy/spatialhadoop,aseldawy/spatialhadoop,aseldawy/spatialhadoop,ShortMap/ShortMap,ShortMap/ShortMap,ShortMap/ShortMap,aseldawy/spatialhadoop,ShortMap/ShortMap,ShortMap/ShortMap,aseldawy/spatialhadoop,aseldawy/spatialhadoop,aseldawy/spatialhadoop,aseldawy/spatialhadoop,ShortMap/ShortMap,ShortMap/ShortMap
|
/**
* 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.mapred;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.examples.SleepJob;
import org.apache.hadoop.mapreduce.test.system.FinishTaskControlAction;
import org.apache.hadoop.mapreduce.test.system.MRCluster;
import org.apache.hadoop.mapreduce.test.system.JTClient;
import org.apache.hadoop.mapreduce.test.system.TTClient;
import org.apache.hadoop.mapreduce.test.system.JTProtocol;
import org.apache.hadoop.mapreduce.test.system.TaskInfo;
import org.apache.hadoop.mapreduce.test.system.JobInfo;
import org.apache.hadoop.mapred.JobClient.NetworkedJob;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Assert;
import java.io.IOException;
import java.util.Random;
import java.util.HashMap;
import java.util.ArrayList;
/**
* Verifying the non-writable cache folders and files for various jobs.
*/
public class TestJobCacheDirectoriesCleanUp {
private static final Log LOG = LogFactory
.getLog(TestJobCacheDirectoriesCleanUp.class);
private static Configuration conf = new Configuration();
private static MRCluster cluster;
private static JTClient jtClient;
private static TTClient ttClient;
private static JTProtocol rtClient;
private static String CUSTOM_CREATION_FILE = "_custom_file_";
private static String CUSTOM_CREATION_FOLDER = "_custom_folder_";
private static FsPermission permission = new FsPermission(FsAction.READ,
FsAction.READ, FsAction.READ);
@BeforeClass
public static void before() throws Exception {
conf = new Configuration();
cluster = MRCluster.createCluster(conf);
cluster.setUp();
jtClient = cluster.getJTClient();
rtClient = jtClient.getProxy();
}
@AfterClass
public static void after() throws Exception {
cluster.tearDown();
}
/**
* Submit a job and create folders and files in work folder with
* non-writable permissions under task attempt id folder.
* Wait till the job completes and verify whether the files
* and folders are cleaned up or not.
* @throws IOException
*/
@Test
public void testJobCleanupAfterJobCompletes() throws IOException {
HashMap<TTClient,ArrayList<String>> map =
new HashMap<TTClient,ArrayList<String>>();
JobID jobId = createJobAndSubmit().getID();
Assert.assertTrue("Job has not been started for 1 min",
jtClient.isJobStarted(jobId));
TaskInfo [] taskInfos = rtClient.getTaskInfo(jobId);
for (TaskInfo taskinfo : taskInfos) {
if (!taskinfo.isSetupOrCleanup()) {
Assert.assertTrue("Task has not been started for 1 min ",
jtClient.isTaskStarted(taskinfo));
String tasktracker = getTaskTracker(taskinfo);
Assert.assertNotNull("TaskTracker has not been found", tasktracker);
TTClient ttclient = getTTClient(tasktracker);
UtilsForTests.waitFor(100);
map.put(ttClient, getTTClientMapRedLocalDirs(ttClient,
taskinfo, jobId));
}
}
LOG.info("Waiting till the job is completed...");
Assert.assertTrue("Job has not been completed for 1 min",
jtClient.isJobStopped(jobId));
UtilsForTests.waitFor(3000);
Assert.assertTrue("Job directories have not been cleaned up properly " +
"after completion of job", verifyJobDirectoryCleanup(map));
}
/**
* Submit a job and create folders and files in work folder with
* non-writable permissions under task attempt id folder.
* Kill the job and verify whether the files and folders
* are cleaned up or not.
* @throws IOException
*/
@Test
public void testJobCleanupAfterJobKill() throws IOException {
HashMap<TTClient,ArrayList<String>> map =
new HashMap<TTClient,ArrayList<String>>();
JobID jobId = createJobAndSubmit().getID();
Assert.assertTrue("Job has not been started for 1 min",
jtClient.isJobStarted(jobId));
TaskInfo [] taskInfos = rtClient.getTaskInfo(jobId);
for (TaskInfo taskinfo : taskInfos) {
if (!taskinfo.isSetupOrCleanup()) {
Assert.assertTrue("Task has not been started for 1 min ",
jtClient.isTaskStarted(taskinfo));
String tasktracker = getTaskTracker(taskinfo);
Assert.assertNotNull("TaskTracker has not been found", tasktracker);
TTClient ttclient = getTTClient(tasktracker);
map.put(ttClient, getTTClientMapRedLocalDirs(ttClient,
taskinfo, jobId));
}
}
jtClient.getClient().killJob(jobId);
LOG.info("Waiting till the job is completed...");
Assert.assertTrue("Job has not been completed for 1 min",
jtClient.isJobStopped(jobId));
JobInfo jobInfo = rtClient.getJobInfo(jobId);
Assert.assertEquals("Job has not been killed",
jobInfo.getStatus().getRunState(), JobStatus.KILLED);
UtilsForTests.waitFor(3000);
Assert.assertTrue("Job directories have not been cleaned up properly " +
"after completion of job", verifyJobDirectoryCleanup(map));
}
/**
* Submit a job and create folders and files in work folder with
* non-writable permissions under task attempt id folder.
* Fail the job and verify whether the files and folders
* are cleaned up or not.
* @throws IOException
*/
@Test
public void testJobCleanupAfterJobFail() throws IOException {
HashMap<TTClient,ArrayList<String>> map =
new HashMap<TTClient,ArrayList<String>>();
conf = rtClient.getDaemonConf();
SleepJob job = new SleepJob();
job.setConf(conf);
JobConf jobConf = job.setupJobConf(1, 0, 10000,0, 10, 10);
JobClient client = jtClient.getClient();
RunningJob runJob = client.submitJob(jobConf);
JobID jobId = runJob.getID();
JobInfo jobInfo = rtClient.getJobInfo(jobId);
Assert.assertTrue("Job has not been started for 1 min",
jtClient.isJobStarted(jobId));
TaskInfo [] taskInfos = rtClient.getTaskInfo(jobId);
boolean isFailTask = false;
for (TaskInfo taskinfo : taskInfos) {
if (!taskinfo.isSetupOrCleanup()) {
Assert.assertTrue("Task has not been started for 1 min ",
jtClient.isTaskStarted(taskinfo));
String tasktracker = getTaskTracker(taskinfo);
Assert.assertNotNull("TaskTracker has not been found", tasktracker);
TTClient ttclient = getTTClient(tasktracker);
map.put(ttClient, getTTClientMapRedLocalDirs(ttClient,
taskinfo, jobId));
if (!isFailTask) {
Assert.assertNotNull("TaskInfo is null.", taskinfo);
TaskID taskId = TaskID.downgrade(taskinfo.getTaskID());
TaskAttemptID taskAttID = new TaskAttemptID(taskId,
taskinfo.numFailedAttempts());
while(taskinfo.numFailedAttempts() < 4) {
NetworkedJob networkJob = jtClient.getClient().
new NetworkedJob(jobInfo.getStatus());
networkJob.killTask(taskAttID, true);
taskinfo = rtClient.getTaskInfo(taskinfo.getTaskID());
taskAttID = new TaskAttemptID(taskId, taskinfo.numFailedAttempts());
jobInfo = rtClient.getJobInfo(jobId);
}
isFailTask=true;
}
}
}
LOG.info("Waiting till the job is completed...");
Assert.assertTrue("Job has not been completed for 1 min",
jtClient.isJobStopped(jobId));
jobInfo = rtClient.getJobInfo(jobId);
Assert.assertEquals("Job has not been failed",
jobInfo.getStatus().getRunState(), JobStatus.FAILED);
UtilsForTests.waitFor(3000);
Assert.assertTrue("Directories have not been cleaned up " +
"after completion of job", verifyJobDirectoryCleanup(map));
}
private static ArrayList <String> getTTClientMapRedLocalDirs(
TTClient ttClient, TaskInfo taskinfo, JobID jobId) throws IOException {
ArrayList <String> fileList = null;
TaskID taskId = TaskID.downgrade(taskinfo.getTaskID());
FinishTaskControlAction action = new FinishTaskControlAction(taskId);
if (ttClient != null ) {
String localDirs[] = ttClient.getMapredLocalDirs();
TaskAttemptID taskAttID = new TaskAttemptID(taskId, 0);
fileList = createFilesInTaskDir(localDirs, jobId, taskAttID, ttClient);
}
ttClient.getProxy().sendAction(action);
return fileList;
}
private static boolean verifyJobDirectoryCleanup(HashMap<TTClient,
ArrayList<String>> map) throws IOException {
boolean status = true;
for (TTClient ttClient : map.keySet()) {
if (map.get(ttClient) != null) {
for(String path : map.get(ttClient)){
FileStatus [] fs = ttClient.listStatus(path, true);
if (fs.length > 0) {
status = false;
}
}
}
}
return status;
}
private static ArrayList<String> createFilesInTaskDir(String [] localDirs,
JobID jobId, TaskAttemptID taskAttID, TTClient ttClient) throws IOException {
Random random = new Random(100);
ArrayList<String> list = new ArrayList<String>();
String customFile = CUSTOM_CREATION_FILE + random.nextInt();
String customFolder = CUSTOM_CREATION_FOLDER + random.nextInt();
int index = 0;
for (String localDir : localDirs) {
String localTaskDir = localDir + "/" +
TaskTracker.getLocalTaskDir(getUser(), jobId.toString(),
taskAttID.toString() + "/work/");
if (ttClient.getFileStatus(localTaskDir,true).isDir()) {
ttClient.createFile(localTaskDir, customFile, permission, true);
ttClient.createFolder(localTaskDir, customFolder, permission, true);
list.add(localTaskDir + customFile);
list.add(localTaskDir + customFolder);
}
}
return list;
}
private static RunningJob createJobAndSubmit() throws IOException {
conf = rtClient.getDaemonConf();
SleepJob job = new SleepJob();
job.setConf(conf);
JobConf jobConf = job.setupJobConf(3, 1, 12000, 12000, 100, 100);
JobClient client = jtClient.getClient();
RunningJob runJob = client.submitJob(jobConf);
return runJob;
}
private static String getUser() throws IOException {
JobStatus[] jobStatus = jtClient.getClient().getAllJobs();
String userName = jobStatus[0].getUsername();
return userName;
}
private static String getTaskTracker(TaskInfo taskInfo)
throws IOException {
String taskTracker = null;
String taskTrackers [] = taskInfo.getTaskTrackers();
int counter = 0;
while (counter < 30) {
if (taskTrackers.length != 0) {
taskTracker = taskTrackers[0];
break;
}
UtilsForTests.waitFor(1000);
taskInfo = rtClient.getTaskInfo(taskInfo.getTaskID());
taskTrackers = taskInfo.getTaskTrackers();
counter ++;
}
return taskTracker;
}
private static TTClient getTTClient(String taskTracker) {
String hostName = taskTracker.split("_")[1];
hostName = hostName.split(":")[0];
ttClient = cluster.getTTClient(hostName);
return ttClient;
}
}
|
src/test/system/java/org/apache/hadoop/mapred/TestJobCacheDirectoriesCleanUp.java
|
commit 48eedca6264a5c29cdc7fdb22cd62711ac9cbd42
Author: Vinay Kumar Thota <[email protected]>
Date: Tue Jul 27 05:13:20 2010 +0000
MAPREDUCE:1957 from https://issues.apache.org/jira/secure/attachment/12450262/1957-ydist-security.patch
git-svn-id: 7e7a2d564dde2945c3a26e08d1235fcc0cb7aba1@1077600 13f79535-47bb-0310-9956-ffa450edef68
|
src/test/system/java/org/apache/hadoop/mapred/TestJobCacheDirectoriesCleanUp.java
|
commit 48eedca6264a5c29cdc7fdb22cd62711ac9cbd42 Author: Vinay Kumar Thota <[email protected]> Date: Tue Jul 27 05:13:20 2010 +0000
|
<ide><path>rc/test/system/java/org/apache/hadoop/mapred/TestJobCacheDirectoriesCleanUp.java
<add>/**
<add> * Licensed to the Apache Software Foundation (ASF) under one
<add> * or more contributor license agreements. See the NOTICE file
<add> * distributed with this work for additional information
<add> * regarding copyright ownership. The ASF licenses this file
<add> * to you under the Apache License, Version 2.0 (the
<add> * "License"); you may not use this file except in compliance
<add> * with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.apache.hadoop.mapred;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.apache.hadoop.conf.Configuration;
<add>import org.apache.hadoop.examples.SleepJob;
<add>import org.apache.hadoop.mapreduce.test.system.FinishTaskControlAction;
<add>import org.apache.hadoop.mapreduce.test.system.MRCluster;
<add>import org.apache.hadoop.mapreduce.test.system.JTClient;
<add>import org.apache.hadoop.mapreduce.test.system.TTClient;
<add>import org.apache.hadoop.mapreduce.test.system.JTProtocol;
<add>import org.apache.hadoop.mapreduce.test.system.TaskInfo;
<add>import org.apache.hadoop.mapreduce.test.system.JobInfo;
<add>import org.apache.hadoop.mapred.JobClient.NetworkedJob;
<add>import org.apache.hadoop.fs.Path;
<add>import org.apache.hadoop.fs.FileStatus;
<add>import org.apache.hadoop.fs.permission.FsAction;
<add>import org.apache.hadoop.fs.permission.FsPermission;
<add>
<add>import org.junit.AfterClass;
<add>import org.junit.BeforeClass;
<add>import org.junit.Test;
<add>import org.junit.Assert;
<add>
<add>import java.io.IOException;
<add>import java.util.Random;
<add>import java.util.HashMap;
<add>import java.util.ArrayList;
<add>
<add>/**
<add> * Verifying the non-writable cache folders and files for various jobs.
<add> */
<add>public class TestJobCacheDirectoriesCleanUp {
<add> private static final Log LOG = LogFactory
<add> .getLog(TestJobCacheDirectoriesCleanUp.class);
<add> private static Configuration conf = new Configuration();
<add> private static MRCluster cluster;
<add> private static JTClient jtClient;
<add> private static TTClient ttClient;
<add> private static JTProtocol rtClient;
<add> private static String CUSTOM_CREATION_FILE = "_custom_file_";
<add> private static String CUSTOM_CREATION_FOLDER = "_custom_folder_";
<add> private static FsPermission permission = new FsPermission(FsAction.READ,
<add> FsAction.READ, FsAction.READ);
<add>
<add> @BeforeClass
<add> public static void before() throws Exception {
<add> conf = new Configuration();
<add> cluster = MRCluster.createCluster(conf);
<add> cluster.setUp();
<add> jtClient = cluster.getJTClient();
<add> rtClient = jtClient.getProxy();
<add>
<add> }
<add>
<add> @AfterClass
<add> public static void after() throws Exception {
<add> cluster.tearDown();
<add> }
<add>
<add> /**
<add> * Submit a job and create folders and files in work folder with
<add> * non-writable permissions under task attempt id folder.
<add> * Wait till the job completes and verify whether the files
<add> * and folders are cleaned up or not.
<add> * @throws IOException
<add> */
<add> @Test
<add> public void testJobCleanupAfterJobCompletes() throws IOException {
<add> HashMap<TTClient,ArrayList<String>> map =
<add> new HashMap<TTClient,ArrayList<String>>();
<add> JobID jobId = createJobAndSubmit().getID();
<add> Assert.assertTrue("Job has not been started for 1 min",
<add> jtClient.isJobStarted(jobId));
<add> TaskInfo [] taskInfos = rtClient.getTaskInfo(jobId);
<add> for (TaskInfo taskinfo : taskInfos) {
<add> if (!taskinfo.isSetupOrCleanup()) {
<add> Assert.assertTrue("Task has not been started for 1 min ",
<add> jtClient.isTaskStarted(taskinfo));
<add> String tasktracker = getTaskTracker(taskinfo);
<add> Assert.assertNotNull("TaskTracker has not been found", tasktracker);
<add> TTClient ttclient = getTTClient(tasktracker);
<add> UtilsForTests.waitFor(100);
<add> map.put(ttClient, getTTClientMapRedLocalDirs(ttClient,
<add> taskinfo, jobId));
<add> }
<add> }
<add>
<add> LOG.info("Waiting till the job is completed...");
<add> Assert.assertTrue("Job has not been completed for 1 min",
<add> jtClient.isJobStopped(jobId));
<add> UtilsForTests.waitFor(3000);
<add> Assert.assertTrue("Job directories have not been cleaned up properly " +
<add> "after completion of job", verifyJobDirectoryCleanup(map));
<add> }
<add>
<add> /**
<add> * Submit a job and create folders and files in work folder with
<add> * non-writable permissions under task attempt id folder.
<add> * Kill the job and verify whether the files and folders
<add> * are cleaned up or not.
<add> * @throws IOException
<add> */
<add> @Test
<add> public void testJobCleanupAfterJobKill() throws IOException {
<add> HashMap<TTClient,ArrayList<String>> map =
<add> new HashMap<TTClient,ArrayList<String>>();
<add> JobID jobId = createJobAndSubmit().getID();
<add> Assert.assertTrue("Job has not been started for 1 min",
<add> jtClient.isJobStarted(jobId));
<add> TaskInfo [] taskInfos = rtClient.getTaskInfo(jobId);
<add> for (TaskInfo taskinfo : taskInfos) {
<add> if (!taskinfo.isSetupOrCleanup()) {
<add> Assert.assertTrue("Task has not been started for 1 min ",
<add> jtClient.isTaskStarted(taskinfo));
<add> String tasktracker = getTaskTracker(taskinfo);
<add> Assert.assertNotNull("TaskTracker has not been found", tasktracker);
<add> TTClient ttclient = getTTClient(tasktracker);
<add> map.put(ttClient, getTTClientMapRedLocalDirs(ttClient,
<add> taskinfo, jobId));
<add> }
<add> }
<add> jtClient.getClient().killJob(jobId);
<add> LOG.info("Waiting till the job is completed...");
<add> Assert.assertTrue("Job has not been completed for 1 min",
<add> jtClient.isJobStopped(jobId));
<add> JobInfo jobInfo = rtClient.getJobInfo(jobId);
<add> Assert.assertEquals("Job has not been killed",
<add> jobInfo.getStatus().getRunState(), JobStatus.KILLED);
<add> UtilsForTests.waitFor(3000);
<add> Assert.assertTrue("Job directories have not been cleaned up properly " +
<add> "after completion of job", verifyJobDirectoryCleanup(map));
<add> }
<add>
<add> /**
<add> * Submit a job and create folders and files in work folder with
<add> * non-writable permissions under task attempt id folder.
<add> * Fail the job and verify whether the files and folders
<add> * are cleaned up or not.
<add> * @throws IOException
<add> */
<add> @Test
<add> public void testJobCleanupAfterJobFail() throws IOException {
<add> HashMap<TTClient,ArrayList<String>> map =
<add> new HashMap<TTClient,ArrayList<String>>();
<add> conf = rtClient.getDaemonConf();
<add> SleepJob job = new SleepJob();
<add> job.setConf(conf);
<add> JobConf jobConf = job.setupJobConf(1, 0, 10000,0, 10, 10);
<add> JobClient client = jtClient.getClient();
<add> RunningJob runJob = client.submitJob(jobConf);
<add> JobID jobId = runJob.getID();
<add> JobInfo jobInfo = rtClient.getJobInfo(jobId);
<add> Assert.assertTrue("Job has not been started for 1 min",
<add> jtClient.isJobStarted(jobId));
<add> TaskInfo [] taskInfos = rtClient.getTaskInfo(jobId);
<add> boolean isFailTask = false;
<add> for (TaskInfo taskinfo : taskInfos) {
<add> if (!taskinfo.isSetupOrCleanup()) {
<add> Assert.assertTrue("Task has not been started for 1 min ",
<add> jtClient.isTaskStarted(taskinfo));
<add> String tasktracker = getTaskTracker(taskinfo);
<add> Assert.assertNotNull("TaskTracker has not been found", tasktracker);
<add> TTClient ttclient = getTTClient(tasktracker);
<add> map.put(ttClient, getTTClientMapRedLocalDirs(ttClient,
<add> taskinfo, jobId));
<add> if (!isFailTask) {
<add> Assert.assertNotNull("TaskInfo is null.", taskinfo);
<add> TaskID taskId = TaskID.downgrade(taskinfo.getTaskID());
<add> TaskAttemptID taskAttID = new TaskAttemptID(taskId,
<add> taskinfo.numFailedAttempts());
<add> while(taskinfo.numFailedAttempts() < 4) {
<add> NetworkedJob networkJob = jtClient.getClient().
<add> new NetworkedJob(jobInfo.getStatus());
<add> networkJob.killTask(taskAttID, true);
<add> taskinfo = rtClient.getTaskInfo(taskinfo.getTaskID());
<add> taskAttID = new TaskAttemptID(taskId, taskinfo.numFailedAttempts());
<add> jobInfo = rtClient.getJobInfo(jobId);
<add> }
<add> isFailTask=true;
<add> }
<add> }
<add> }
<add> LOG.info("Waiting till the job is completed...");
<add> Assert.assertTrue("Job has not been completed for 1 min",
<add> jtClient.isJobStopped(jobId));
<add> jobInfo = rtClient.getJobInfo(jobId);
<add> Assert.assertEquals("Job has not been failed",
<add> jobInfo.getStatus().getRunState(), JobStatus.FAILED);
<add> UtilsForTests.waitFor(3000);
<add> Assert.assertTrue("Directories have not been cleaned up " +
<add> "after completion of job", verifyJobDirectoryCleanup(map));
<add> }
<add>
<add> private static ArrayList <String> getTTClientMapRedLocalDirs(
<add> TTClient ttClient, TaskInfo taskinfo, JobID jobId) throws IOException {
<add> ArrayList <String> fileList = null;
<add> TaskID taskId = TaskID.downgrade(taskinfo.getTaskID());
<add> FinishTaskControlAction action = new FinishTaskControlAction(taskId);
<add> if (ttClient != null ) {
<add> String localDirs[] = ttClient.getMapredLocalDirs();
<add> TaskAttemptID taskAttID = new TaskAttemptID(taskId, 0);
<add> fileList = createFilesInTaskDir(localDirs, jobId, taskAttID, ttClient);
<add> }
<add> ttClient.getProxy().sendAction(action);
<add> return fileList;
<add> }
<add>
<add> private static boolean verifyJobDirectoryCleanup(HashMap<TTClient,
<add> ArrayList<String>> map) throws IOException {
<add> boolean status = true;
<add> for (TTClient ttClient : map.keySet()) {
<add> if (map.get(ttClient) != null) {
<add> for(String path : map.get(ttClient)){
<add> FileStatus [] fs = ttClient.listStatus(path, true);
<add> if (fs.length > 0) {
<add> status = false;
<add> }
<add> }
<add> }
<add> }
<add> return status;
<add> }
<add>
<add> private static ArrayList<String> createFilesInTaskDir(String [] localDirs,
<add> JobID jobId, TaskAttemptID taskAttID, TTClient ttClient) throws IOException {
<add> Random random = new Random(100);
<add> ArrayList<String> list = new ArrayList<String>();
<add> String customFile = CUSTOM_CREATION_FILE + random.nextInt();
<add> String customFolder = CUSTOM_CREATION_FOLDER + random.nextInt();
<add> int index = 0;
<add> for (String localDir : localDirs) {
<add> String localTaskDir = localDir + "/" +
<add> TaskTracker.getLocalTaskDir(getUser(), jobId.toString(),
<add> taskAttID.toString() + "/work/");
<add> if (ttClient.getFileStatus(localTaskDir,true).isDir()) {
<add> ttClient.createFile(localTaskDir, customFile, permission, true);
<add> ttClient.createFolder(localTaskDir, customFolder, permission, true);
<add> list.add(localTaskDir + customFile);
<add> list.add(localTaskDir + customFolder);
<add> }
<add> }
<add>
<add> return list;
<add> }
<add>
<add> private static RunningJob createJobAndSubmit() throws IOException {
<add> conf = rtClient.getDaemonConf();
<add> SleepJob job = new SleepJob();
<add> job.setConf(conf);
<add> JobConf jobConf = job.setupJobConf(3, 1, 12000, 12000, 100, 100);
<add> JobClient client = jtClient.getClient();
<add> RunningJob runJob = client.submitJob(jobConf);
<add> return runJob;
<add> }
<add>
<add> private static String getUser() throws IOException {
<add> JobStatus[] jobStatus = jtClient.getClient().getAllJobs();
<add> String userName = jobStatus[0].getUsername();
<add> return userName;
<add> }
<add>
<add> private static String getTaskTracker(TaskInfo taskInfo)
<add> throws IOException {
<add> String taskTracker = null;
<add> String taskTrackers [] = taskInfo.getTaskTrackers();
<add> int counter = 0;
<add> while (counter < 30) {
<add> if (taskTrackers.length != 0) {
<add> taskTracker = taskTrackers[0];
<add> break;
<add> }
<add> UtilsForTests.waitFor(1000);
<add> taskInfo = rtClient.getTaskInfo(taskInfo.getTaskID());
<add> taskTrackers = taskInfo.getTaskTrackers();
<add> counter ++;
<add> }
<add> return taskTracker;
<add> }
<add>
<add> private static TTClient getTTClient(String taskTracker) {
<add> String hostName = taskTracker.split("_")[1];
<add> hostName = hostName.split(":")[0];
<add> ttClient = cluster.getTTClient(hostName);
<add> return ttClient;
<add> }
<add>}
|
|
Java
|
mit
|
441e418fe73d45b90d25540f74f0da01560423e1
| 0 |
juliesouchet/StreetCar,juliesouchet/StreetCar
|
package main.java.data;
import java.awt.Point;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import main.java.data.Tile.Path;
import main.java.game.ExceptionFullParty;
import main.java.game.UnknownBoardNameException;
import main.java.player.PlayerInterface;
import main.java.util.Direction;
public class Data
{
// --------------------------------------------
// Attributes:
// --------------------------------------------
public static final String boardDirectory = "src/main/resources/board/";
public static final int maxNbrPlayer = 6;
private String gameName;
private Tile[][] board;
private Deck deck;
private HashMap<String, PlayerInfo> playerInfoList;
// --------------------------------------------
// Builder:
// --------------------------------------------
public Data(String gameName, String boardName) throws UnknownBoardNameException, RuntimeException
{
File f = new File(boardDirectory + boardName);
Scanner sc;
try {sc = new Scanner(f);}
catch(Exception e) {throw new UnknownBoardNameException();}
this.gameName = new String(gameName);
this.board = scanBoardFile(sc);
this.deck = new Deck();
this.playerInfoList = new HashMap<String, PlayerInfo>();
sc.close();
}
// --------------------------------------------
// Setter:
// --------------------------------------------
public void addPlayer(PlayerInterface p, String playerName) throws ExceptionFullParty
{
if (this.playerInfoList.size() >= maxNbrPlayer) throw new ExceptionFullParty();
PlayerInfo pi = new PlayerInfo(p);
this.playerInfoList.put(playerName, pi);
}
public void removePlayer(String playerName)
{
PlayerInterface pi = this.playerInfoList.get(playerName).player;
if (pi == null) throw new RuntimeException("Unknown player: " + playerName);
this.playerInfoList.remove(playerName);
}
// --------------------------------------------
// Getter:
// --------------------------------------------
public Tile[][] getBoard() {return boardCopy();}
public int getWidth() {return this.board.length;}
public int getHeight() {return this.board[0].length;}
public int getNbrPlayer() {return this.playerInfoList.size();}
public Tile getTile(int x, int y) {return new Tile(this.board[x][y]);}
public void setTile(int x, int y, Tile t) {this.board[x][y] = t;}
public String getGameName() {return new String(this.gameName);}
public Set<String> getPlayerNameList() {return this.playerInfoList.keySet();}
public boolean containsPlayer(String playerName) {return this.playerInfoList.containsKey(playerName);}
public PlayerInterface getPlayer(String playerName)
{
PlayerInterface pi = this.playerInfoList.get(playerName).player;
if (pi == null) throw new RuntimeException("Unknown player: " + playerName);
return pi;
}
public boolean isWithinnBoard(int x, int y)
{
if ((x < 0) || (x >= getWidth())) return false;
if ((y < 0) || (y >= getHeight())) return false;
return true;
}
public boolean isOnEdge(int x, int y)
{
if ((x == 0) || (x == getWidth()-1)) return true;
if ((y == 0) || (y == getHeight()-1)) return true;
return false;
}
/**===============================================================
* @return if the deposit of the tile t on the board at the position <x, y> is possible
=================================================================*/
public boolean isAcceptableTilePlacement(int x, int y, Tile t)
{
LinkedList<Path> additionalPath = new LinkedList<Path>();
LinkedList<Integer> accessibleDirection;
Tile oldT = this.board[x][y];
if (!oldT.isReplaceable(t, additionalPath)) return false; // Check whether t contains the old t (remove Tile and Rule C)
Tile nt = new Tile(additionalPath, t);
accessibleDirection = nt.getAccessibleDirections();
for (int d: accessibleDirection) // Check whether the new tile is suitable with the <x, y> neighborhood
{
Point neighbor = Direction.getNeighbour(x, y, d);
//////// if (!this.isWithinnBoard(neighbor.x, neighbor.y)) return false; // Neighbor tile out of board
Tile neighborT = this.board[x][y];
if ((this.isOnEdge(neighbor.x, neighbor.y)) && (!neighborT.isTerminus())) return false; // Rule A
if (neighborT.isEmpty()) continue; // Rule E (step 1)
if (neighborT.isBuilding()) return false; // Rule B
if (!neighborT.isPathTo(Direction.turnHalf(d))) return false; // Rule E (step 2)
}
LinkedList<Integer> plt = this.getPathsLeadingToTile(x, y); // Rule D
for (int dir: plt) if (!nt.isPathTo(dir)) return false;
return true;
}
/**============================================================
* @return a list of the neighbor coordinates. This function
* does not check whether the neighbour is accessible through a path on the current tile
==============================================================*/
public LinkedList<Point> getNeighbourPositions(int x, int y)
{
LinkedList<Point> res = new LinkedList<Point>();
int w = getWidth();
int h = getHeight();
if (y > 0) res.add(new Point(x, y-1)); // North
if (y < h-1) res.add(new Point(x, y+1)); // South
if (x > 0) res.add(new Point(x-1, y)); // West
if (x < w-1) res.add(new Point(x+1, y)); // East
return res;
}
/**============================================================
* @return the list of the neighbor coordinates that can be acceded from the <x,y> cell
==============================================================*/
public LinkedList<Point> getAccessibleNeighboursCoordinates(int x, int y)
{
LinkedList<Point> res = new LinkedList<Point>();
LinkedList<Integer> ad = board[x][y].getAccessibleDirections(); // List of the reachable directions
for (int d: ad) // For each accesible position
{
Point next = Direction.getNeighbour(x, y, d);
if (isWithinnBoard(next.x, next.y)) res.add(next);
}
return res;
}
/**============================================================
* @return the list of the neighbor tiles that can be acceded from the <x,y> cell
==============================================================*/
public LinkedList<Tile> getAccessibleNeighboursTiles(int x, int y)
{
LinkedList<Tile> res = new LinkedList<Tile>();
LinkedList<Integer> ad = board[x][y].getAccessibleDirections(); // List of the reachable directions
for (int d: ad) // For each accesible position
{
Point next = Direction.getNeighbour(x, y, d);
if (isWithinnBoard(next.x, next.y)) res.add(new Tile(board[next.x][next.y]));
}
return res;
}
/**============================================================
* @returns the list of directions d such as the neighbor d has a path to the current tile <x, y>
==============================================================*/
public LinkedList<Integer> getPathsLeadingToTile(int x, int y)
{
LinkedList<Integer> res = new LinkedList<Integer>();
Iterator<Integer> di = Direction.getIterator();
int direction, neighborDir;
Point neighbor;
Tile neighborTile;
while (di.hasNext())
{
direction = di.next();
neighbor = Direction.getNeighbour(x, y, direction);
if (!this.isWithinnBoard(neighbor.x, neighbor.y)) continue;
neighborTile= board[neighbor.x][neighbor.y];
neighborDir = Direction.turnHalf(direction);
if (neighborTile.isPathTo(neighborDir)) res.add(direction);
}
return res;
}
/**=========================================================================
* @param building: Position of a building
* @return the position of the stop next to the building
* @throws runtimeException if the parameter is not a building
===========================================================================*/
public Point hasStopNextToBuilding(Point building)
{
Tile t = this.board[building.x][building.y];
Iterator<Integer> dirIt = Direction.getIterator();
Point p;
if (!t.isBuilding()) throw new RuntimeException("The point " + building + " is not a building");
while(dirIt.hasNext())
{
p = Direction.getNeighbour(building.x, building.y, dirIt.next());
if (this.isWithinnBoard(p.x, p.y)) continue;
t = this.board[p.x][p.y];
if (t.isStop()) return p;
}
return null;
}
// --------------------------------------------
// Private methods:
// --------------------------------------------
private Tile[][] scanBoardFile(Scanner sc)
{
Tile[][] res;
String tileFileName;
int width, height;
try
{
width = sc.nextInt();
height = sc.nextInt();
res = new Tile[width][height];
for (int y=0; y<height; y++)
{
for (int x=0; x<width; x++)
{
tileFileName = sc.next();
res[x][y] = new Tile(tileFileName);
}
}
}
catch (Exception e){throw new RuntimeException("Malformed board file");}
return null;
}
private Tile[][] boardCopy()
{
int width = getWidth();
int height = getHeight();
Tile[][] res = new Tile[width][height];
for (int w=0; w<width; w++)
{
for (int h=0; h<height; h++)
{
res[w][h] = new Tile(board[w][h]);
}
}
return res;
}
// --------------------------------------------
// Player Info class:
// --------------------------------------------
private class PlayerInfo
{
// Attributes
public PlayerInterface player;
public Hand hand;
public LinkedList<Action> history;
// Builder
public PlayerInfo(PlayerInterface pi)
{
this.player = pi;
this.hand = new Hand();
this.history= new LinkedList<Action>();
}
}
}
|
src/main/java/data/Data.java
|
package main.java.data;
import java.awt.Point;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import main.java.data.Tile.Path;
import main.java.game.ExceptionFullParty;
import main.java.game.UnknownBoardNameException;
import main.java.player.PlayerInterface;
import main.java.util.Direction;
public class Data
{
// --------------------------------------------
// Attributes:
// --------------------------------------------
public static final String boardDirectory = "src/main/resources/board/";
public static final int maxNbrPlayer = 6;
private String gameName;
private Tile[][] board;
private Deck deck;
private HashMap<String, PlayerInfo> playerInfoList;
// --------------------------------------------
// Builder:
// --------------------------------------------
public Data(String gameName, String boardName) throws UnknownBoardNameException, RuntimeException
{
File f = new File(boardDirectory + boardName);
Scanner sc;
try {sc = new Scanner(f);}
catch(Exception e) {throw new UnknownBoardNameException();}
this.gameName = new String(gameName);
this.board = scanBoardFile(sc);
this.deck = new Deck();
this.playerInfoList = new HashMap<String, PlayerInfo>();
sc.close();
}
// --------------------------------------------
// Setter:
// --------------------------------------------
public void addPlayer(PlayerInterface p, String playerName) throws ExceptionFullParty
{
if (this.playerInfoList.size() >= maxNbrPlayer) throw new ExceptionFullParty();
PlayerInfo pi = new PlayerInfo(p);
this.playerInfoList.put(playerName, pi);
}
public void removePlayer(String playerName)
{
PlayerInterface pi = this.playerInfoList.get(playerName).player;
if (pi == null) throw new RuntimeException("Unknown player: " + playerName);
this.playerInfoList.remove(playerName);
}
// --------------------------------------------
// Getter:
// --------------------------------------------
public int getWidth() {return this.board.length;}
public int getHeight() {return this.board[0].length;}
public int getNbrPlayer() {return this.playerInfoList.size();}
public Tile getTile(int x, int y) {return new Tile(this.board[x][y]);}
public void setTile(int x, int y, Tile t) {this.board[x][y] = t;}
public String getGameName() {return new String(this.gameName);}
public Set<String> getPlayerNameList() {return this.playerInfoList.keySet();}
public boolean containsPlayer(String playerName) {return this.playerInfoList.containsKey(playerName);}
public PlayerInterface getPlayer(String playerName)
{
PlayerInterface pi = this.playerInfoList.get(playerName).player;
if (pi == null) throw new RuntimeException("Unknown player: " + playerName);
return pi;
}
public boolean isWithinnBoard(int x, int y)
{
if ((x < 0) || (x >= getWidth())) return false;
if ((y < 0) || (y >= getHeight())) return false;
return true;
}
public boolean isOnEdge(int x, int y)
{
if ((x == 0) || (x == getWidth()-1)) return true;
if ((y == 0) || (y == getHeight()-1)) return true;
return false;
}
/**===============================================================
* @return if the deposit of the tile t on the board at the position <x, y> is possible
=================================================================*/
public boolean isAcceptableTilePlacement(int x, int y, Tile t)
{
LinkedList<Path> additionalPath = new LinkedList<Path>();
LinkedList<Integer> accessibleDirection;
Tile oldT = this.board[x][y];
if (!oldT.isReplaceable(t, additionalPath)) return false; // Check whether t contains the old t (remove Tile and Rule C)
Tile nt = new Tile(additionalPath, t);
accessibleDirection = nt.getAccessibleDirections();
for (int d: accessibleDirection) // Check whether the new tile is suitable with the <x, y> neighborhood
{
Point neighbor = Direction.getNeighbour(x, y, d);
//////// if (!this.isWithinnBoard(neighbor.x, neighbor.y)) return false; // Neighbor tile out of board
Tile neighborT = this.board[x][y];
if ((this.isOnEdge(neighbor.x, neighbor.y)) && (!neighborT.isTerminus())) return false; // Rule A
if (neighborT.isEmpty()) continue; // Rule E (step 1)
if (neighborT.isBuilding()) return false; // Rule B
if (!neighborT.isPathTo(Direction.turnHalf(d))) return false; // Rule E (step 2)
}
LinkedList<Integer> plt = this.getPathsLeadingToTile(x, y); // Rule D
for (int dir: plt) if (!nt.isPathTo(dir)) return false;
return true;
}
/**============================================================
* @return a list of the neighbor coordinates. This function
* does not check whether the neighbour is accessible through a path on the current tile
==============================================================*/
public LinkedList<Point> getNeighbourPositions(int x, int y)
{
LinkedList<Point> res = new LinkedList<Point>();
int w = getWidth();
int h = getHeight();
if (y > 0) res.add(new Point(x, y-1)); // North
if (y < h-1) res.add(new Point(x, y+1)); // South
if (x > 0) res.add(new Point(x-1, y)); // West
if (x < w-1) res.add(new Point(x+1, y)); // East
return res;
}
/**============================================================
* @return the list of the neighbor coordinates that can be acceded from the <x,y> cell
==============================================================*/
public LinkedList<Point> getAccessibleNeighboursCoordinates(int x, int y)
{
LinkedList<Point> res = new LinkedList<Point>();
LinkedList<Integer> ad = board[x][y].getAccessibleDirections(); // List of the reachable directions
for (int d: ad) // For each accesible position
{
Point next = Direction.getNeighbour(x, y, d);
if (isWithinnBoard(next.x, next.y)) res.add(next);
}
return res;
}
/**============================================================
* @return the list of the neighbor tiles that can be acceded from the <x,y> cell
==============================================================*/
public LinkedList<Tile> getAccessibleNeighboursTiles(int x, int y)
{
LinkedList<Tile> res = new LinkedList<Tile>();
LinkedList<Integer> ad = board[x][y].getAccessibleDirections(); // List of the reachable directions
for (int d: ad) // For each accesible position
{
Point next = Direction.getNeighbour(x, y, d);
if (isWithinnBoard(next.x, next.y)) res.add(new Tile(board[next.x][next.y]));
}
return res;
}
/**============================================================
* @returns the list of directions d such as the neighbor d has a path to the current tile <x, y>
==============================================================*/
public LinkedList<Integer> getPathsLeadingToTile(int x, int y)
{
LinkedList<Integer> res = new LinkedList<Integer>();
Iterator<Integer> di = Direction.getIterator();
int direction, neighborDir;
Point neighbor;
Tile neighborTile;
while (di.hasNext())
{
direction = di.next();
neighbor = Direction.getNeighbour(x, y, direction);
if (!this.isWithinnBoard(neighbor.x, neighbor.y)) continue;
neighborTile= board[neighbor.x][neighbor.y];
neighborDir = Direction.turnHalf(direction);
if (neighborTile.isPathTo(neighborDir)) res.add(direction);
}
return res;
}
/**=========================================================================
* @param building: Position of a building
* @return the position of the stop next to the building
* @throws runtimeException if the parameter is not a building
===========================================================================*/
public Point hasStopNextToBuilding(Point building)
{
Tile t = this.board[building.x][building.y];
Iterator<Integer> dirIt = Direction.getIterator();
Point p;
if (!t.isBuilding()) throw new RuntimeException("The point " + building + " is not a building");
while(dirIt.hasNext())
{
p = Direction.getNeighbour(building.x, building.y, dirIt.next());
if (this.isWithinnBoard(p.x, p.y)) continue;
t = this.board[p.x][p.y];
if (t.isStop()) return p;
}
return null;
}
// --------------------------------------------
// Private methods:
// --------------------------------------------
private Tile[][] scanBoardFile(Scanner sc)
{
Tile[][] res;
String tileFileName;
int width, height;
try
{
width = sc.nextInt();
height = sc.nextInt();
res = new Tile[width][height];
for (int y=0; y<height; y++)
{
for (int x=0; x<width; x++)
{
tileFileName = sc.next();
res[x][y] = new Tile(tileFileName);
}
}
}
catch (Exception e){throw new RuntimeException("Malformed board file");}
return null;
}
// --------------------------------------------
// Player Info class:
// --------------------------------------------
private class PlayerInfo
{
// Attributes
public PlayerInterface player;
public Hand hand;
public LinkedList<Action> history;
// Builder
public PlayerInfo(PlayerInterface pi)
{
this.player = pi;
this.hand = new Hand();
this.history= new LinkedList<Action>();
}
}
}
|
data creation part 3
|
src/main/java/data/Data.java
|
data creation part 3
|
<ide><path>rc/main/java/data/Data.java
<ide> // --------------------------------------------
<ide> // Getter:
<ide> // --------------------------------------------
<add> public Tile[][] getBoard() {return boardCopy();}
<ide> public int getWidth() {return this.board.length;}
<ide> public int getHeight() {return this.board[0].length;}
<ide> public int getNbrPlayer() {return this.playerInfoList.size();}
<ide>
<ide> return null;
<ide> }
<add> private Tile[][] boardCopy()
<add> {
<add> int width = getWidth();
<add> int height = getHeight();
<add> Tile[][] res = new Tile[width][height];
<add>
<add> for (int w=0; w<width; w++)
<add> {
<add> for (int h=0; h<height; h++)
<add> {
<add> res[w][h] = new Tile(board[w][h]);
<add> }
<add> }
<add> return res;
<add> }
<ide>
<ide> // --------------------------------------------
<ide> // Player Info class:
|
|
Java
|
apache-2.0
|
1b332e1f99b7db8f8c77ad6cfb6e8881e1660c02
| 0 |
gilfernandes/camel,johnpoth/camel,onders86/camel,atoulme/camel,stalet/camel,sabre1041/camel,drsquidop/camel,qst-jdc-labs/camel,gyc567/camel,maschmid/camel,Fabryprog/camel,jkorab/camel,jlpedrosa/camel,pax95/camel,nikvaessen/camel,snadakuduru/camel,jameszkw/camel,Thopap/camel,grange74/camel,drsquidop/camel,maschmid/camel,oalles/camel,arnaud-deprez/camel,davidwilliams1978/camel,atoulme/camel,dvankleef/camel,dsimansk/camel,sabre1041/camel,mnki/camel,jamesnetherton/camel,chanakaudaya/camel,CodeSmell/camel,tarilabs/camel,christophd/camel,YoshikiHigo/camel,Fabryprog/camel,cunningt/camel,mgyongyosi/camel,driseley/camel,anton-k11/camel,mnki/camel,yury-vashchyla/camel,gautric/camel,onders86/camel,MohammedHammam/camel,edigrid/camel,christophd/camel,stalet/camel,jpav/camel,jkorab/camel,lburgazzoli/camel,onders86/camel,MrCoder/camel,NetNow/camel,veithen/camel,isururanawaka/camel,bfitzpat/camel,acartapanis/camel,tkopczynski/camel,akhettar/camel,bdecoste/camel,pmoerenhout/camel,bgaudaen/camel,skinzer/camel,zregvart/camel,sverkera/camel,chanakaudaya/camel,pkletsko/camel,alvinkwekel/camel,grange74/camel,objectiser/camel,CandleCandle/camel,oscerd/camel,cunningt/camel,nboukhed/camel,yuruki/camel,snurmine/camel,zregvart/camel,pmoerenhout/camel,rparree/camel,NickCis/camel,iweiss/camel,mgyongyosi/camel,chirino/camel,ge0ffrey/camel,eformat/camel,FingolfinTEK/camel,chanakaudaya/camel,erwelch/camel,alvinkwekel/camel,jmandawg/camel,JYBESSON/camel,borcsokj/camel,ekprayas/camel,DariusX/camel,josefkarasek/camel,DariusX/camel,dsimansk/camel,scranton/camel,Thopap/camel,isavin/camel,duro1/camel,gilfernandes/camel,tdiesler/camel,royopa/camel,RohanHart/camel,CandleCandle/camel,CodeSmell/camel,rparree/camel,oscerd/camel,prashant2402/camel,gnodet/camel,sabre1041/camel,anoordover/camel,duro1/camel,cunningt/camel,isavin/camel,dsimansk/camel,bhaveshdt/camel,punkhorn/camel-upstream,johnpoth/camel,RohanHart/camel,bhaveshdt/camel,mike-kukla/camel,bhaveshdt/camel,RohanHart/camel,skinzer/camel,hqstevenson/camel,bdecoste/camel,NickCis/camel,jamesnetherton/camel,noelo/camel,dkhanolkar/camel,nikvaessen/camel,yury-vashchyla/camel,lowwool/camel,pplatek/camel,yuruki/camel,gilfernandes/camel,gyc567/camel,eformat/camel,askannon/camel,coderczp/camel,royopa/camel,pplatek/camel,apache/camel,grgrzybek/camel,joakibj/camel,pax95/camel,partis/camel,bgaudaen/camel,Thopap/camel,gautric/camel,bgaudaen/camel,mzapletal/camel,jameszkw/camel,eformat/camel,gautric/camel,pplatek/camel,tlehoux/camel,askannon/camel,lburgazzoli/apache-camel,partis/camel,tkopczynski/camel,akhettar/camel,yuruki/camel,ssharma/camel,neoramon/camel,bhaveshdt/camel,nboukhed/camel,pplatek/camel,isavin/camel,gyc567/camel,grange74/camel,iweiss/camel,neoramon/camel,rparree/camel,DariusX/camel,nicolaferraro/camel,brreitme/camel,ramonmaruko/camel,mgyongyosi/camel,driseley/camel,isururanawaka/camel,YMartsynkevych/camel,brreitme/camel,noelo/camel,arnaud-deprez/camel,dkhanolkar/camel,jpav/camel,jarst/camel,josefkarasek/camel,scranton/camel,FingolfinTEK/camel,lburgazzoli/camel,davidkarlsen/camel,dvankleef/camel,snurmine/camel,grgrzybek/camel,oscerd/camel,rmarting/camel,dmvolod/camel,mzapletal/camel,chirino/camel,anoordover/camel,royopa/camel,manuelh9r/camel,jpav/camel,hqstevenson/camel,johnpoth/camel,tadayosi/camel,ullgren/camel,lasombra/camel,koscejev/camel,satishgummadelli/camel,oscerd/camel,yogamaha/camel,partis/camel,davidwilliams1978/camel,jmandawg/camel,MrCoder/camel,brreitme/camel,hqstevenson/camel,borcsokj/camel,bfitzpat/camel,alvinkwekel/camel,NetNow/camel,Thopap/camel,ramonmaruko/camel,maschmid/camel,sverkera/camel,partis/camel,woj-i/camel,JYBESSON/camel,ramonmaruko/camel,askannon/camel,rmarting/camel,drsquidop/camel,YMartsynkevych/camel,snurmine/camel,jamesnetherton/camel,tkopczynski/camel,skinzer/camel,nboukhed/camel,pkletsko/camel,onders86/camel,iweiss/camel,mohanaraosv/camel,jollygeorge/camel,trohovsky/camel,yury-vashchyla/camel,veithen/camel,lowwool/camel,jkorab/camel,objectiser/camel,snadakuduru/camel,davidkarlsen/camel,ssharma/camel,sirlatrom/camel,anoordover/camel,RohanHart/camel,driseley/camel,gilfernandes/camel,pkletsko/camel,eformat/camel,dmvolod/camel,mcollovati/camel,ekprayas/camel,brreitme/camel,CodeSmell/camel,jmandawg/camel,davidwilliams1978/camel,jlpedrosa/camel,edigrid/camel,royopa/camel,mzapletal/camel,curso007/camel,coderczp/camel,anton-k11/camel,qst-jdc-labs/camel,ge0ffrey/camel,YMartsynkevych/camel,nikvaessen/camel,w4tson/camel,lburgazzoli/camel,RohanHart/camel,joakibj/camel,veithen/camel,stalet/camel,kevinearls/camel,veithen/camel,tarilabs/camel,grgrzybek/camel,yury-vashchyla/camel,tkopczynski/camel,borcsokj/camel,stalet/camel,zregvart/camel,YoshikiHigo/camel,mohanaraosv/camel,cunningt/camel,christophd/camel,scranton/camel,davidwilliams1978/camel,veithen/camel,dpocock/camel,w4tson/camel,allancth/camel,dkhanolkar/camel,tlehoux/camel,ekprayas/camel,bdecoste/camel,lasombra/camel,trohovsky/camel,gnodet/camel,jlpedrosa/camel,koscejev/camel,jlpedrosa/camel,nikvaessen/camel,dpocock/camel,askannon/camel,jollygeorge/camel,yogamaha/camel,oalles/camel,NickCis/camel,qst-jdc-labs/camel,jonmcewen/camel,arnaud-deprez/camel,adessaigne/camel,lasombra/camel,MrCoder/camel,lburgazzoli/camel,mzapletal/camel,koscejev/camel,tkopczynski/camel,satishgummadelli/camel,bfitzpat/camel,dkhanolkar/camel,acartapanis/camel,w4tson/camel,zregvart/camel,jmandawg/camel,yury-vashchyla/camel,adessaigne/camel,jkorab/camel,iweiss/camel,skinzer/camel,tlehoux/camel,stravag/camel,stravag/camel,rmarting/camel,nicolaferraro/camel,akhettar/camel,ramonmaruko/camel,satishgummadelli/camel,YoshikiHigo/camel,dvankleef/camel,curso007/camel,mike-kukla/camel,qst-jdc-labs/camel,Fabryprog/camel,kevinearls/camel,adessaigne/camel,iweiss/camel,mike-kukla/camel,koscejev/camel,allancth/camel,tdiesler/camel,prashant2402/camel,woj-i/camel,akhettar/camel,jarst/camel,bhaveshdt/camel,lburgazzoli/apache-camel,yuruki/camel,neoramon/camel,grange74/camel,DariusX/camel,isururanawaka/camel,stalet/camel,curso007/camel,driseley/camel,ekprayas/camel,dpocock/camel,josefkarasek/camel,erwelch/camel,dpocock/camel,haku/camel,lowwool/camel,sirlatrom/camel,ssharma/camel,qst-jdc-labs/camel,royopa/camel,johnpoth/camel,arnaud-deprez/camel,jmandawg/camel,johnpoth/camel,chirino/camel,pmoerenhout/camel,RohanHart/camel,yogamaha/camel,duro1/camel,joakibj/camel,dmvolod/camel,christophd/camel,gyc567/camel,grgrzybek/camel,dpocock/camel,acartapanis/camel,onders86/camel,tadayosi/camel,oscerd/camel,JYBESSON/camel,erwelch/camel,NetNow/camel,tlehoux/camel,driseley/camel,yuruki/camel,dmvolod/camel,CandleCandle/camel,josefkarasek/camel,chirino/camel,adessaigne/camel,adessaigne/camel,CodeSmell/camel,joakibj/camel,grange74/camel,jonmcewen/camel,sabre1041/camel,MrCoder/camel,oalles/camel,jarst/camel,ssharma/camel,sebi-hgdata/camel,chanakaudaya/camel,driseley/camel,pax95/camel,NickCis/camel,ekprayas/camel,ge0ffrey/camel,prashant2402/camel,grgrzybek/camel,JYBESSON/camel,nboukhed/camel,veithen/camel,sabre1041/camel,dvankleef/camel,noelo/camel,jonmcewen/camel,mnki/camel,jonmcewen/camel,sirlatrom/camel,jameszkw/camel,FingolfinTEK/camel,bgaudaen/camel,dsimansk/camel,allancth/camel,bdecoste/camel,scranton/camel,borcsokj/camel,jkorab/camel,jarst/camel,mzapletal/camel,bfitzpat/camel,jameszkw/camel,NetNow/camel,bgaudaen/camel,gnodet/camel,nboukhed/camel,YoshikiHigo/camel,tadayosi/camel,alvinkwekel/camel,jkorab/camel,ullgren/camel,skinzer/camel,jameszkw/camel,edigrid/camel,erwelch/camel,dkhanolkar/camel,pax95/camel,qst-jdc-labs/camel,pplatek/camel,lowwool/camel,FingolfinTEK/camel,sebi-hgdata/camel,trohovsky/camel,christophd/camel,akhettar/camel,stravag/camel,MohammedHammam/camel,coderczp/camel,stalet/camel,mzapletal/camel,CandleCandle/camel,FingolfinTEK/camel,cunningt/camel,ssharma/camel,mnki/camel,tarilabs/camel,Thopap/camel,adessaigne/camel,apache/camel,mike-kukla/camel,rmarting/camel,punkhorn/camel-upstream,maschmid/camel,ge0ffrey/camel,bfitzpat/camel,prashant2402/camel,haku/camel,pplatek/camel,eformat/camel,gnodet/camel,isavin/camel,maschmid/camel,chanakaudaya/camel,apache/camel,ramonmaruko/camel,tdiesler/camel,apache/camel,pax95/camel,tarilabs/camel,gautric/camel,jlpedrosa/camel,atoulme/camel,hqstevenson/camel,anoordover/camel,acartapanis/camel,MohammedHammam/camel,dpocock/camel,isavin/camel,tarilabs/camel,isururanawaka/camel,lburgazzoli/apache-camel,gyc567/camel,nicolaferraro/camel,kevinearls/camel,tdiesler/camel,snadakuduru/camel,neoramon/camel,lburgazzoli/apache-camel,yuruki/camel,erwelch/camel,scranton/camel,davidkarlsen/camel,kevinearls/camel,snurmine/camel,eformat/camel,gnodet/camel,rmarting/camel,brreitme/camel,atoulme/camel,nboukhed/camel,chirino/camel,bdecoste/camel,satishgummadelli/camel,noelo/camel,gilfernandes/camel,cunningt/camel,anoordover/camel,bhaveshdt/camel,acartapanis/camel,rparree/camel,noelo/camel,YMartsynkevych/camel,gyc567/camel,jpav/camel,sebi-hgdata/camel,pmoerenhout/camel,stravag/camel,MrCoder/camel,bgaudaen/camel,YMartsynkevych/camel,borcsokj/camel,oalles/camel,jameszkw/camel,jamesnetherton/camel,sebi-hgdata/camel,pmoerenhout/camel,koscejev/camel,mcollovati/camel,trohovsky/camel,prashant2402/camel,maschmid/camel,satishgummadelli/camel,jollygeorge/camel,jlpedrosa/camel,pmoerenhout/camel,dmvolod/camel,partis/camel,askannon/camel,salikjan/camel,woj-i/camel,jonmcewen/camel,ge0ffrey/camel,YoshikiHigo/camel,mohanaraosv/camel,JYBESSON/camel,royopa/camel,satishgummadelli/camel,acartapanis/camel,trohovsky/camel,jarst/camel,CandleCandle/camel,snurmine/camel,mike-kukla/camel,jollygeorge/camel,sabre1041/camel,scranton/camel,gautric/camel,jamesnetherton/camel,woj-i/camel,akhettar/camel,sirlatrom/camel,ge0ffrey/camel,apache/camel,josefkarasek/camel,gilfernandes/camel,ullgren/camel,stravag/camel,salikjan/camel,NickCis/camel,jpav/camel,koscejev/camel,tkopczynski/camel,manuelh9r/camel,Thopap/camel,josefkarasek/camel,davidwilliams1978/camel,pplatek/camel,NetNow/camel,mohanaraosv/camel,nikhilvibhav/camel,NickCis/camel,tdiesler/camel,edigrid/camel,MohammedHammam/camel,dsimansk/camel,MrCoder/camel,w4tson/camel,onders86/camel,punkhorn/camel-upstream,sebi-hgdata/camel,tlehoux/camel,oalles/camel,jollygeorge/camel,joakibj/camel,mgyongyosi/camel,objectiser/camel,curso007/camel,dvankleef/camel,lasombra/camel,allancth/camel,pkletsko/camel,oscerd/camel,haku/camel,sverkera/camel,lowwool/camel,lburgazzoli/apache-camel,iweiss/camel,woj-i/camel,ramonmaruko/camel,JYBESSON/camel,anton-k11/camel,nikhilvibhav/camel,rmarting/camel,haku/camel,hqstevenson/camel,lburgazzoli/apache-camel,anton-k11/camel,lasombra/camel,chanakaudaya/camel,jarst/camel,rparree/camel,curso007/camel,tadayosi/camel,yogamaha/camel,NetNow/camel,ssharma/camel,sverkera/camel,apache/camel,gautric/camel,kevinearls/camel,mcollovati/camel,neoramon/camel,MohammedHammam/camel,chirino/camel,lburgazzoli/camel,drsquidop/camel,atoulme/camel,noelo/camel,manuelh9r/camel,tarilabs/camel,mike-kukla/camel,mohanaraosv/camel,coderczp/camel,mohanaraosv/camel,coderczp/camel,isururanawaka/camel,isavin/camel,objectiser/camel,nikvaessen/camel,skinzer/camel,mcollovati/camel,mgyongyosi/camel,manuelh9r/camel,ullgren/camel,borcsokj/camel,davidwilliams1978/camel,prashant2402/camel,snurmine/camel,lasombra/camel,snadakuduru/camel,MohammedHammam/camel,w4tson/camel,tlehoux/camel,brreitme/camel,tadayosi/camel,johnpoth/camel,nikhilvibhav/camel,joakibj/camel,edigrid/camel,hqstevenson/camel,ekprayas/camel,woj-i/camel,bfitzpat/camel,dkhanolkar/camel,trohovsky/camel,sirlatrom/camel,oalles/camel,grgrzybek/camel,punkhorn/camel-upstream,partis/camel,CandleCandle/camel,atoulme/camel,tadayosi/camel,yogamaha/camel,nikvaessen/camel,drsquidop/camel,mnki/camel,erwelch/camel,snadakuduru/camel,w4tson/camel,rparree/camel,pkletsko/camel,duro1/camel,sebi-hgdata/camel,allancth/camel,anoordover/camel,askannon/camel,FingolfinTEK/camel,arnaud-deprez/camel,dsimansk/camel,drsquidop/camel,davidkarlsen/camel,haku/camel,jmandawg/camel,nicolaferraro/camel,pax95/camel,sverkera/camel,jollygeorge/camel,kevinearls/camel,snadakuduru/camel,allancth/camel,anton-k11/camel,YMartsynkevych/camel,neoramon/camel,pkletsko/camel,nikhilvibhav/camel,YoshikiHigo/camel,tdiesler/camel,duro1/camel,jamesnetherton/camel,jpav/camel,stravag/camel,dmvolod/camel,duro1/camel,mgyongyosi/camel,lburgazzoli/camel,isururanawaka/camel,Fabryprog/camel,jonmcewen/camel,anton-k11/camel,curso007/camel,manuelh9r/camel,mnki/camel,yury-vashchyla/camel,haku/camel,dvankleef/camel,manuelh9r/camel,edigrid/camel,sverkera/camel,lowwool/camel,arnaud-deprez/camel,grange74/camel,coderczp/camel,yogamaha/camel,christophd/camel,sirlatrom/camel,bdecoste/camel
|
/**
* 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.camel.tools.apt;
import java.io.PrintWriter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.camel.spi.Label;
import static org.apache.camel.tools.apt.JsonSchemaHelper.sanitizeDescription;
import static org.apache.camel.tools.apt.Strings.canonicalClassName;
import static org.apache.camel.tools.apt.Strings.isNullOrEmpty;
import static org.apache.camel.tools.apt.Strings.safeNull;
// TODO: figure out a way to specify default value in the model classes which this APT can read
/**
* Process all camel-core's model classes (EIPs and DSL) and generate json schema documentation
*/
@SupportedAnnotationTypes({"javax.xml.bind.annotation.*", "org.apache.camel.spi.Label"})
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class EipAnnotationProcessor extends AbstractAnnotationProcessor {
// special when using expression/predicates in the model
private static final String ONE_OF_TYPE_NAME = "org.apache.camel.model.ExpressionSubElementDefinition";
private static final String ONE_OF_LANGUAGES = "org.apache.camel.model.language.ExpressionDefinition";
// special for outputs (these classes have sub classes, so we use this to find all classes)
private static final String[] ONE_OF_OUTPUTS = new String[]{
"org.apache.camel.model.ProcessorDefinition",
"org.apache.camel.model.NoOutputDefinition",
"org.apache.camel.model.OutputDefinition",
"org.apache.camel.model.ExpressionNode",
"org.apache.camel.model.NoOutputExpressionNode",
"org.apache.camel.model.SendDefinition",
"org.apache.camel.model.InterceptDefinition",
"org.apache.camel.model.WhenDefinition",
};
private boolean skipUnwanted = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return true;
}
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(XmlRootElement.class);
for (Element element : elements) {
if (element instanceof TypeElement) {
processModelClass(roundEnv, (TypeElement) element);
}
}
return true;
}
protected void processModelClass(final RoundEnvironment roundEnv, final TypeElement classElement) {
// must be from org.apache.camel.model
final String javaTypeName = canonicalClassName(classElement.getQualifiedName().toString());
String packageName = javaTypeName.substring(0, javaTypeName.lastIndexOf("."));
if (!javaTypeName.startsWith("org.apache.camel.model")) {
return;
}
// skip abstract classes
if (classElement.getModifiers().contains(Modifier.ABSTRACT)) {
return;
}
// skip unwanted classes which are "abstract" holders
if (skipUnwanted) {
if (classElement.getQualifiedName().toString().equals(ONE_OF_TYPE_NAME)) {
return;
}
}
final XmlRootElement rootElement = classElement.getAnnotation(XmlRootElement.class);
String aName = rootElement.name();
if (isNullOrEmpty(aName) || "##default".equals(aName)) {
XmlType typeElement = classElement.getAnnotation(XmlType.class);
aName = typeElement.name();
}
final String name = aName;
// lets use the xsd name as the file name
String fileName;
if (isNullOrEmpty(name) || "##default".equals(name)) {
fileName = classElement.getSimpleName().toString() + ".json";
} else {
fileName = name + ".json";
}
// write json schema
Func1<PrintWriter, Void> handler = new Func1<PrintWriter, Void>() {
@Override
public Void call(PrintWriter writer) {
writeJSonSchemeDocumentation(writer, roundEnv, classElement, rootElement, javaTypeName, name);
return null;
}
};
processFile(packageName, fileName, handler);
}
protected void writeJSonSchemeDocumentation(PrintWriter writer, RoundEnvironment roundEnv, TypeElement classElement, XmlRootElement rootElement,
String javaTypeName, String name) {
// gather eip information
EipModel eipModel = findEipModelProperties(roundEnv, classElement, javaTypeName, name);
// get endpoint information which is divided into paths and options (though there should really only be one path)
Set<EipOption> eipOptions = new LinkedHashSet<EipOption>();
findClassProperties(writer, roundEnv, eipOptions, classElement, classElement, "");
String json = createParameterJsonSchema(eipModel, eipOptions);
writer.println(json);
}
public String createParameterJsonSchema(EipModel eipModel, Set<EipOption> options) {
StringBuilder buffer = new StringBuilder("{");
// eip model
buffer.append("\n \"model\": {");
buffer.append("\n \"kind\": \"").append("model").append("\",");
buffer.append("\n \"name\": \"").append(eipModel.getName()).append("\",");
buffer.append("\n \"title\": \"").append(asTitle(eipModel.getName())).append("\",");
buffer.append("\n \"description\": \"").append(safeNull(eipModel.getDescription())).append("\",");
buffer.append("\n \"javaType\": \"").append(eipModel.getJavaType()).append("\",");
buffer.append("\n \"label\": \"").append(safeNull(eipModel.getLabel())).append("\",");
buffer.append("\n },");
buffer.append("\n \"properties\": {");
boolean first = true;
for (EipOption entry : options) {
if (first) {
first = false;
} else {
buffer.append(",");
}
buffer.append("\n ");
// as its json we need to sanitize the docs
String doc = entry.getDocumentation();
doc = sanitizeDescription(doc, false);
buffer.append(JsonSchemaHelper.toJson(entry.getName(), entry.getKind(), entry.isRequired(), entry.getType(), entry.getDefaultValue(), doc,
entry.isDeprecated(), entry.isEnumType(), entry.getEnums(), entry.isOneOf(), entry.getOneOfTypes()));
}
buffer.append("\n }");
buffer.append("\n}\n");
return buffer.toString();
}
protected EipModel findEipModelProperties(RoundEnvironment roundEnv, TypeElement classElement, String javaTypeName, String name) {
EipModel model = new EipModel();
model.setJavaType(javaTypeName);
model.setName(name);
Label label = classElement.getAnnotation(Label.class);
if (label != null) {
model.setLabel(label.value());
}
// favor to use class javadoc of component as description
if (model.getJavaType() != null) {
Elements elementUtils = processingEnv.getElementUtils();
TypeElement typeElement = findTypeElement(roundEnv, model.getJavaType());
if (typeElement != null) {
String doc = elementUtils.getDocComment(typeElement);
if (doc != null) {
// need to sanitize the description first (we only want a summary)
doc = sanitizeDescription(doc, true);
// the javadoc may actually be empty, so only change the doc if we got something
if (!Strings.isNullOrEmpty(doc)) {
model.setDescription(doc);
}
}
}
}
return model;
}
protected void findClassProperties(PrintWriter writer, RoundEnvironment roundEnv, Set<EipOption> eipOptions,
TypeElement originalClassType, TypeElement classElement, String prefix) {
while (true) {
List<VariableElement> fieldElements = ElementFilter.fieldsIn(classElement.getEnclosedElements());
for (VariableElement fieldElement : fieldElements) {
String fieldName = fieldElement.getSimpleName().toString();
XmlAttribute attribute = fieldElement.getAnnotation(XmlAttribute.class);
if (attribute != null) {
boolean skip = processAttribute(roundEnv, originalClassType, classElement, fieldElement, fieldName, attribute, eipOptions, prefix);
if (skip) {
continue;
}
}
XmlElements elements = fieldElement.getAnnotation(XmlElements.class);
if (elements != null) {
processElements(roundEnv, classElement, elements, fieldElement, eipOptions, prefix);
}
XmlElement element = fieldElement.getAnnotation(XmlElement.class);
if (element != null) {
processElement(roundEnv, classElement, element, fieldElement, eipOptions, prefix);
}
// special for eips which has outputs or requires an expressions
XmlElementRef elementRef = fieldElement.getAnnotation(XmlElementRef.class);
if (elementRef != null) {
// special for outputs
processOutputs(roundEnv, originalClassType, elementRef, fieldElement, fieldName, eipOptions, prefix);
// special for expression
processExpression(roundEnv, elementRef, fieldElement, fieldName, eipOptions, prefix);
}
}
// special when we process these nodes as they do not use JAXB annotations on fields, but on methods
if ("OptionalIdentifiedDefinition".equals(classElement.getSimpleName().toString())) {
processIdentified(roundEnv, originalClassType, classElement, eipOptions, prefix);
} else if ("RouteDefinition".equals(classElement.getSimpleName().toString())) {
processRoute(roundEnv, originalClassType, classElement, eipOptions, prefix);
}
// check super classes which may also have fields
TypeElement baseTypeElement = null;
TypeMirror superclass = classElement.getSuperclass();
if (superclass != null) {
String superClassName = canonicalClassName(superclass.toString());
baseTypeElement = findTypeElement(roundEnv, superClassName);
}
if (baseTypeElement != null) {
classElement = baseTypeElement;
} else {
break;
}
}
}
private boolean processAttribute(RoundEnvironment roundEnv, TypeElement originalClassType, TypeElement classElement, VariableElement fieldElement, String fieldName, XmlAttribute attribute,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
String name = attribute.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
// lets skip some unwanted attributes
if (skipUnwanted) {
// we want to skip inheritErrorHandler which is only applicable for the load-balancer
boolean loadBalancer = "LoadBalanceDefinition".equals(originalClassType.getSimpleName().toString());
if (!loadBalancer && "inheritErrorHandler".equals(name)) {
return true;
}
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
TypeElement fieldTypeElement = findTypeElement(roundEnv, fieldTypeName);
String docComment = findJavaDoc(elementUtils, fieldElement, fieldName, classElement, true);
boolean required = attribute.required();
// gather enums
Set<String> enums = new TreeSet<String>();
boolean isEnum = fieldTypeElement != null && fieldTypeElement.getKind() == ElementKind.ENUM;
if (isEnum) {
TypeElement enumClass = findTypeElement(roundEnv, fieldTypeElement.asType().toString());
// find all the enum constants which has the possible enum value that can be used
List<VariableElement> fields = ElementFilter.fieldsIn(enumClass.getEnclosedElements());
for (VariableElement var : fields) {
if (var.getKind() == ElementKind.ENUM_CONSTANT) {
String val = var.toString();
enums.add(val);
}
}
}
boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null;
EipOption ep = new EipOption(name, "attribute", fieldTypeName, required, "", docComment, deprecated, isEnum, enums, false, null);
eipOptions.add(ep);
return false;
}
private void processElement(RoundEnvironment roundEnv, TypeElement classElement, XmlElement element, VariableElement fieldElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
String fieldName;
fieldName = fieldElement.getSimpleName().toString();
if (element != null) {
String kind = "element";
String name = element.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
TypeElement fieldTypeElement = findTypeElement(roundEnv, fieldTypeName);
String docComment = findJavaDoc(elementUtils, fieldElement, fieldName, classElement, true);
boolean required = element.required();
// gather enums
Set<String> enums = new LinkedHashSet<String>();
boolean isEnum = fieldTypeElement != null && fieldTypeElement.getKind() == ElementKind.ENUM;
if (isEnum) {
TypeElement enumClass = findTypeElement(roundEnv, fieldTypeElement.asType().toString());
// find all the enum constants which has the possible enum value that can be used
List<VariableElement> fields = ElementFilter.fieldsIn(enumClass.getEnclosedElements());
for (VariableElement var : fields) {
if (var.getKind() == ElementKind.ENUM_CONSTANT) {
String val = var.toString();
enums.add(val);
}
}
}
// gather oneOf expression/predicates which uses language
Set<String> oneOfTypes = new TreeSet<String>();
boolean isOneOf = ONE_OF_TYPE_NAME.equals(fieldTypeName);
if (isOneOf) {
TypeElement languages = findTypeElement(roundEnv, ONE_OF_LANGUAGES);
String superClassName = canonicalClassName(languages.toString());
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
findTypeElementChildren(roundEnv, children, superClassName);
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
}
boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null;
EipOption ep = new EipOption(name, kind, fieldTypeName, required, "", docComment, deprecated, isEnum, enums, isOneOf, oneOfTypes);
eipOptions.add(ep);
}
}
private void processElements(RoundEnvironment roundEnv, TypeElement classElement, XmlElements elements, VariableElement fieldElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
String fieldName;
fieldName = fieldElement.getSimpleName().toString();
if (elements != null) {
String kind = "element";
String name = fieldName;
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
String docComment = findJavaDoc(elementUtils, fieldElement, fieldName, classElement, true);
boolean required = true;
// gather oneOf of the elements
Set<String> oneOfTypes = new TreeSet<String>();
for (XmlElement element : elements.value()) {
String child = element.name();
oneOfTypes.add(child);
}
EipOption ep = new EipOption(name, kind, fieldTypeName, required, "", docComment, false, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
}
private void processRoute(RoundEnvironment roundEnv, TypeElement originalClassType, TypeElement classElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
// group
String docComment = findJavaDoc(elementUtils, null, "group", classElement, true);
EipOption ep = new EipOption("group", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// group
docComment = findJavaDoc(elementUtils, null, "streamCache", classElement, true);
ep = new EipOption("streamCache", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// trace
docComment = findJavaDoc(elementUtils, null, "trace", classElement, true);
ep = new EipOption("trace", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// trace
docComment = findJavaDoc(elementUtils, null, "messageHistory", classElement, true);
ep = new EipOption("messageHistory", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// trace
docComment = findJavaDoc(elementUtils, null, "handleFault", classElement, true);
ep = new EipOption("handleFault", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// delayer
docComment = findJavaDoc(elementUtils, null, "delayer", classElement, true);
ep = new EipOption("delayer", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// autoStartup
docComment = findJavaDoc(elementUtils, null, "autoStartup", classElement, true);
ep = new EipOption("autoStartup", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// startupOrder
docComment = findJavaDoc(elementUtils, null, "startupOrder", classElement, true);
ep = new EipOption("startupOrder", "attribute", "java.lang.Integer", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// errorHandlerRef
docComment = findJavaDoc(elementUtils, null, "errorHandlerRef", classElement, true);
ep = new EipOption("errorHandlerRef", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// routePolicyRef
docComment = findJavaDoc(elementUtils, null, "routePolicyRef", classElement, true);
ep = new EipOption("routePolicyRef", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// shutdownRoute
Set<String> enums = new LinkedHashSet<String>();
enums.add("Default");
enums.add("Defer");
docComment = findJavaDoc(elementUtils, null, "shutdownRoute", classElement, true);
ep = new EipOption("shutdownRoute", "attribute", "org.apache.camel.ShutdownRoute", false, "", docComment, false, true, enums, false, null);
eipOptions.add(ep);
// shutdownRunningTask
enums = new LinkedHashSet<String>();
enums.add("CompleteCurrentTaskOnly");
enums.add("CompleteAllTasks");
docComment = findJavaDoc(elementUtils, null, "shutdownRunningTask", classElement, true);
ep = new EipOption("shutdownRunningTask", "attribute", "org.apache.camel.ShutdownRunningTask", false, "", docComment, false, true, enums, false, null);
eipOptions.add(ep);
// inputs
Set<String> oneOfTypes = new TreeSet<String>();
oneOfTypes.add("from");
docComment = findJavaDoc(elementUtils, null, "inputs", classElement, true);
ep = new EipOption("inputs", "element", "java.util.List<org.apache.camel.model.FromDefinition>", true, "", docComment, false, false, null, true, oneOfTypes);
eipOptions.add(ep);
// outputs
// gather oneOf which extends any of the output base classes
oneOfTypes = new TreeSet<String>();
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
for (String superclass : ONE_OF_OUTPUTS) {
findTypeElementChildren(roundEnv, children, superclass);
}
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
// remove some types which are not intended as an output in eips
oneOfTypes.remove("route");
docComment = findJavaDoc(elementUtils, null, "outputs", classElement, true);
ep = new EipOption("outputs", "element", "java.util.List<org.apache.camel.model.ProcessorDefinition<?>>", true, "", docComment, false, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
/**
* Special for process the OptionalIdentifiedDefinition
*/
private void processIdentified(RoundEnvironment roundEnv, TypeElement originalClassType, TypeElement classElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
// id
String docComment = findJavaDoc(elementUtils, null, "id", classElement, true);
EipOption ep = new EipOption("id", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// description
docComment = findJavaDoc(elementUtils, null, "description", classElement, true);
ep = new EipOption("description", "element", "org.apache.camel.model.DescriptionDefinition", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// lets skip custom id as it has no value for end users to configure
if (!skipUnwanted) {
// custom id
docComment = findJavaDoc(elementUtils, null, "customId", classElement, true);
ep = new EipOption("customId", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
}
}
/**
* Special for processing an @XmlElementRef expression field
*/
private void processExpression(RoundEnvironment roundEnv, XmlElementRef elementRef, VariableElement fieldElement,
String fieldName, Set<EipOption> eipOptions, String prefix) {
if ("expression".equals(fieldName)) {
String kind = "element";
String name = elementRef.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
// gather oneOf expression/predicates which uses language
Set<String> oneOfTypes = new TreeSet<String>();
TypeElement languages = findTypeElement(roundEnv, ONE_OF_LANGUAGES);
String superClassName = canonicalClassName(languages.toString());
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
findTypeElementChildren(roundEnv, children, superClassName);
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null;
EipOption ep = new EipOption(name, kind, fieldTypeName, true, "", "", deprecated, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
}
/**
* Special for processing an @XmlElementRef outputs field
*/
private void processOutputs(RoundEnvironment roundEnv, TypeElement originalClassType, XmlElementRef elementRef,
VariableElement fieldElement, String fieldName, Set<EipOption> eipOptions, String prefix) {
if ("outputs".equals(fieldName) && supportOutputs(originalClassType)) {
String kind = "element";
String name = elementRef.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
// gather oneOf which extends any of the output base classes
Set<String> oneOfTypes = new TreeSet<String>();
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
for (String superclass : ONE_OF_OUTPUTS) {
findTypeElementChildren(roundEnv, children, superclass);
}
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
// remove some types which are not intended as an output in eips
oneOfTypes.remove("route");
EipOption ep = new EipOption(name, kind, fieldTypeName, true, "", "", false, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
}
/**
* Whether the class supports outputs.
* <p/>
* There are some classes which does not support outputs, even though they have a outputs element.
*/
private boolean supportOutputs(TypeElement classElement) {
String superclass = canonicalClassName(classElement.getSuperclass().toString());
return !"org.apache.camel.model.NoOutputExpressionNode".equals(superclass);
}
/**
* Capitializes the name as a title
*
* @param name the name
* @return as a title
*/
private static String asTitle(String name) {
StringBuilder sb = new StringBuilder();
for (char c : name.toCharArray()) {
boolean upper = Character.isUpperCase(c);
boolean first = sb.length() == 0;
if (first) {
sb.append(Character.toUpperCase(c));
} else if (upper) {
sb.append(' ');
sb.append(c);
} else {
sb.append(Character.toLowerCase(c));
}
}
return sb.toString().trim();
}
private static final class EipModel {
private String name;
private String javaType;
private String label;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJavaType() {
return javaType;
}
public void setJavaType(String javaType) {
this.javaType = javaType;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
private static final class EipOption {
private String name;
private String kind;
private String type;
private boolean required;
private String defaultValue;
private String documentation;
private boolean deprecated;
private boolean enumType;
private Set<String> enums;
private boolean oneOf;
private Set<String> oneOfTypes;
private EipOption(String name, String kind, String type, boolean required, String defaultValue, String documentation, boolean deprecated,
boolean enumType, Set<String> enums, boolean oneOf, Set<String> oneOfTypes) {
this.name = name;
this.kind = kind;
this.type = type;
this.required = required;
this.defaultValue = defaultValue;
this.documentation = documentation;
this.deprecated = deprecated;
this.enumType = enumType;
this.enums = enums;
this.oneOf = oneOf;
this.oneOfTypes = oneOfTypes;
}
public String getName() {
return name;
}
public String getKind() {
return kind;
}
public String getType() {
return type;
}
public boolean isRequired() {
return required;
}
public String getDefaultValue() {
return defaultValue;
}
public String getDocumentation() {
return documentation;
}
public boolean isDeprecated() {
return deprecated;
}
public boolean isEnumType() {
return enumType;
}
public Set<String> getEnums() {
return enums;
}
public boolean isOneOf() {
return oneOf;
}
public Set<String> getOneOfTypes() {
return oneOfTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EipOption that = (EipOption) o;
if (!name.equals(that.name)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return name.hashCode();
}
}
}
|
tooling/apt/src/main/java/org/apache/camel/tools/apt/EipAnnotationProcessor.java
|
/**
* 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.camel.tools.apt;
import java.io.PrintWriter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.camel.spi.Label;
import static org.apache.camel.tools.apt.JsonSchemaHelper.sanitizeDescription;
import static org.apache.camel.tools.apt.Strings.canonicalClassName;
import static org.apache.camel.tools.apt.Strings.isNullOrEmpty;
import static org.apache.camel.tools.apt.Strings.safeNull;
// TODO: figure out a way to specify default value in the model classes which this APT can read
/**
* Process all camel-core's model classes (EIPs and DSL) and generate json schema documentation
*/
@SupportedAnnotationTypes({"javax.xml.bind.annotation.*", "org.apache.camel.spi.Label"})
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class EipAnnotationProcessor extends AbstractAnnotationProcessor {
// special when using expression/predicates in the model
private static final String ONE_OF_TYPE_NAME = "org.apache.camel.model.ExpressionSubElementDefinition";
private static final String ONE_OF_LANGUAGES = "org.apache.camel.model.language.ExpressionDefinition";
// special for outputs (these classes have sub classes, so we use this to find all classes)
private static final String[] ONE_OF_OUTPUTS = new String[]{
"org.apache.camel.model.ProcessorDefinition",
"org.apache.camel.model.NoOutputDefinition",
"org.apache.camel.model.OutputDefinition",
"org.apache.camel.model.ExpressionNode",
"org.apache.camel.model.NoOutputExpressionNode",
"org.apache.camel.model.SendDefinition",
"org.apache.camel.model.InterceptDefinition",
"org.apache.camel.model.WhenDefinition",
};
private boolean skipUnwanted = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return true;
}
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(XmlRootElement.class);
for (Element element : elements) {
if (element instanceof TypeElement) {
processModelClass(roundEnv, (TypeElement) element);
}
}
return true;
}
protected void processModelClass(final RoundEnvironment roundEnv, final TypeElement classElement) {
// must be from org.apache.camel.model
final String javaTypeName = canonicalClassName(classElement.getQualifiedName().toString());
String packageName = javaTypeName.substring(0, javaTypeName.lastIndexOf("."));
if (!javaTypeName.startsWith("org.apache.camel.model")) {
return;
}
// skip abstract classes
if (classElement.getModifiers().contains(Modifier.ABSTRACT)) {
return;
}
// skip unwanted classes which are "abstract" holders
if (skipUnwanted) {
if (classElement.getQualifiedName().toString().equals(ONE_OF_TYPE_NAME)) {
return;
}
}
final XmlRootElement rootElement = classElement.getAnnotation(XmlRootElement.class);
String aName = rootElement.name();
if (isNullOrEmpty(aName) || "##default".equals(aName)) {
XmlType typeElement = classElement.getAnnotation(XmlType.class);
aName = typeElement.name();
}
final String name = aName;
// lets use the xsd name as the file name
String fileName;
if (isNullOrEmpty(name) || "##default".equals(name)) {
fileName = classElement.getSimpleName().toString() + ".json";
} else {
fileName = name + ".json";
}
// write json schema
Func1<PrintWriter, Void> handler = new Func1<PrintWriter, Void>() {
@Override
public Void call(PrintWriter writer) {
writeJSonSchemeDocumentation(writer, roundEnv, classElement, rootElement, javaTypeName, name);
return null;
}
};
processFile(packageName, fileName, handler);
}
protected void writeJSonSchemeDocumentation(PrintWriter writer, RoundEnvironment roundEnv, TypeElement classElement, XmlRootElement rootElement,
String javaTypeName, String name) {
// gather eip information
EipModel eipModel = findEipModelProperties(roundEnv, classElement, javaTypeName, name);
// get endpoint information which is divided into paths and options (though there should really only be one path)
Set<EipOption> eipOptions = new LinkedHashSet<EipOption>();
findClassProperties(writer, roundEnv, eipOptions, classElement, classElement, "");
String json = createParameterJsonSchema(eipModel, eipOptions);
writer.println(json);
}
public String createParameterJsonSchema(EipModel eipModel, Set<EipOption> options) {
StringBuilder buffer = new StringBuilder("{");
// eip model
buffer.append("\n \"model\": {");
buffer.append("\n \"kind\": \"").append("model").append("\",");
buffer.append("\n \"name\": \"").append(eipModel.getName()).append("\",");
buffer.append("\n \"description\": \"").append(safeNull(eipModel.getDescription())).append("\",");
buffer.append("\n \"javaType\": \"").append(eipModel.getJavaType()).append("\",");
buffer.append("\n \"label\": \"").append(safeNull(eipModel.getLabel())).append("\",");
buffer.append("\n },");
buffer.append("\n \"properties\": {");
boolean first = true;
for (EipOption entry : options) {
if (first) {
first = false;
} else {
buffer.append(",");
}
buffer.append("\n ");
// as its json we need to sanitize the docs
String doc = entry.getDocumentation();
doc = sanitizeDescription(doc, false);
buffer.append(JsonSchemaHelper.toJson(entry.getName(), entry.getKind(), entry.isRequired(), entry.getType(), entry.getDefaultValue(), doc,
entry.isDeprecated(), entry.isEnumType(), entry.getEnums(), entry.isOneOf(), entry.getOneOfTypes()));
}
buffer.append("\n }");
buffer.append("\n}\n");
return buffer.toString();
}
protected EipModel findEipModelProperties(RoundEnvironment roundEnv, TypeElement classElement, String javaTypeName, String name) {
EipModel model = new EipModel();
model.setJavaType(javaTypeName);
model.setName(name);
Label label = classElement.getAnnotation(Label.class);
if (label != null) {
model.setLabel(label.value());
}
// favor to use class javadoc of component as description
if (model.getJavaType() != null) {
Elements elementUtils = processingEnv.getElementUtils();
TypeElement typeElement = findTypeElement(roundEnv, model.getJavaType());
if (typeElement != null) {
String doc = elementUtils.getDocComment(typeElement);
if (doc != null) {
// need to sanitize the description first (we only want a summary)
doc = sanitizeDescription(doc, true);
// the javadoc may actually be empty, so only change the doc if we got something
if (!Strings.isNullOrEmpty(doc)) {
model.setDescription(doc);
}
}
}
}
return model;
}
protected void findClassProperties(PrintWriter writer, RoundEnvironment roundEnv, Set<EipOption> eipOptions,
TypeElement originalClassType, TypeElement classElement, String prefix) {
while (true) {
List<VariableElement> fieldElements = ElementFilter.fieldsIn(classElement.getEnclosedElements());
for (VariableElement fieldElement : fieldElements) {
String fieldName = fieldElement.getSimpleName().toString();
XmlAttribute attribute = fieldElement.getAnnotation(XmlAttribute.class);
if (attribute != null) {
boolean skip = processAttribute(roundEnv, originalClassType, classElement, fieldElement, fieldName, attribute, eipOptions, prefix);
if (skip) {
continue;
}
}
XmlElements elements = fieldElement.getAnnotation(XmlElements.class);
if (elements != null) {
processElements(roundEnv, classElement, elements, fieldElement, eipOptions, prefix);
}
XmlElement element = fieldElement.getAnnotation(XmlElement.class);
if (element != null) {
processElement(roundEnv, classElement, element, fieldElement, eipOptions, prefix);
}
// special for eips which has outputs or requires an expressions
XmlElementRef elementRef = fieldElement.getAnnotation(XmlElementRef.class);
if (elementRef != null) {
// special for outputs
processOutputs(roundEnv, originalClassType, elementRef, fieldElement, fieldName, eipOptions, prefix);
// special for expression
processExpression(roundEnv, elementRef, fieldElement, fieldName, eipOptions, prefix);
}
}
// special when we process these nodes as they do not use JAXB annotations on fields, but on methods
if ("OptionalIdentifiedDefinition".equals(classElement.getSimpleName().toString())) {
processIdentified(roundEnv, originalClassType, classElement, eipOptions, prefix);
} else if ("RouteDefinition".equals(classElement.getSimpleName().toString())) {
processRoute(roundEnv, originalClassType, classElement, eipOptions, prefix);
}
// check super classes which may also have fields
TypeElement baseTypeElement = null;
TypeMirror superclass = classElement.getSuperclass();
if (superclass != null) {
String superClassName = canonicalClassName(superclass.toString());
baseTypeElement = findTypeElement(roundEnv, superClassName);
}
if (baseTypeElement != null) {
classElement = baseTypeElement;
} else {
break;
}
}
}
private boolean processAttribute(RoundEnvironment roundEnv, TypeElement originalClassType, TypeElement classElement, VariableElement fieldElement, String fieldName, XmlAttribute attribute,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
String name = attribute.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
// lets skip some unwanted attributes
if (skipUnwanted) {
// we want to skip inheritErrorHandler which is only applicable for the load-balancer
boolean loadBalancer = "LoadBalanceDefinition".equals(originalClassType.getSimpleName().toString());
if (!loadBalancer && "inheritErrorHandler".equals(name)) {
return true;
}
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
TypeElement fieldTypeElement = findTypeElement(roundEnv, fieldTypeName);
String docComment = findJavaDoc(elementUtils, fieldElement, fieldName, classElement, true);
boolean required = attribute.required();
// gather enums
Set<String> enums = new TreeSet<String>();
boolean isEnum = fieldTypeElement != null && fieldTypeElement.getKind() == ElementKind.ENUM;
if (isEnum) {
TypeElement enumClass = findTypeElement(roundEnv, fieldTypeElement.asType().toString());
// find all the enum constants which has the possible enum value that can be used
List<VariableElement> fields = ElementFilter.fieldsIn(enumClass.getEnclosedElements());
for (VariableElement var : fields) {
if (var.getKind() == ElementKind.ENUM_CONSTANT) {
String val = var.toString();
enums.add(val);
}
}
}
boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null;
EipOption ep = new EipOption(name, "attribute", fieldTypeName, required, "", docComment, deprecated, isEnum, enums, false, null);
eipOptions.add(ep);
return false;
}
private void processElement(RoundEnvironment roundEnv, TypeElement classElement, XmlElement element, VariableElement fieldElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
String fieldName;
fieldName = fieldElement.getSimpleName().toString();
if (element != null) {
String kind = "element";
String name = element.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
TypeElement fieldTypeElement = findTypeElement(roundEnv, fieldTypeName);
String docComment = findJavaDoc(elementUtils, fieldElement, fieldName, classElement, true);
boolean required = element.required();
// gather enums
Set<String> enums = new LinkedHashSet<String>();
boolean isEnum = fieldTypeElement != null && fieldTypeElement.getKind() == ElementKind.ENUM;
if (isEnum) {
TypeElement enumClass = findTypeElement(roundEnv, fieldTypeElement.asType().toString());
// find all the enum constants which has the possible enum value that can be used
List<VariableElement> fields = ElementFilter.fieldsIn(enumClass.getEnclosedElements());
for (VariableElement var : fields) {
if (var.getKind() == ElementKind.ENUM_CONSTANT) {
String val = var.toString();
enums.add(val);
}
}
}
// gather oneOf expression/predicates which uses language
Set<String> oneOfTypes = new TreeSet<String>();
boolean isOneOf = ONE_OF_TYPE_NAME.equals(fieldTypeName);
if (isOneOf) {
TypeElement languages = findTypeElement(roundEnv, ONE_OF_LANGUAGES);
String superClassName = canonicalClassName(languages.toString());
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
findTypeElementChildren(roundEnv, children, superClassName);
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
}
boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null;
EipOption ep = new EipOption(name, kind, fieldTypeName, required, "", docComment, deprecated, isEnum, enums, isOneOf, oneOfTypes);
eipOptions.add(ep);
}
}
private void processElements(RoundEnvironment roundEnv, TypeElement classElement, XmlElements elements, VariableElement fieldElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
String fieldName;
fieldName = fieldElement.getSimpleName().toString();
if (elements != null) {
String kind = "element";
String name = fieldName;
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
String docComment = findJavaDoc(elementUtils, fieldElement, fieldName, classElement, true);
boolean required = true;
// gather oneOf of the elements
Set<String> oneOfTypes = new TreeSet<String>();
for (XmlElement element : elements.value()) {
String child = element.name();
oneOfTypes.add(child);
}
EipOption ep = new EipOption(name, kind, fieldTypeName, required, "", docComment, false, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
}
private void processRoute(RoundEnvironment roundEnv, TypeElement originalClassType, TypeElement classElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
// group
String docComment = findJavaDoc(elementUtils, null, "group", classElement, true);
EipOption ep = new EipOption("group", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// group
docComment = findJavaDoc(elementUtils, null, "streamCache", classElement, true);
ep = new EipOption("streamCache", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// trace
docComment = findJavaDoc(elementUtils, null, "trace", classElement, true);
ep = new EipOption("trace", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// trace
docComment = findJavaDoc(elementUtils, null, "messageHistory", classElement, true);
ep = new EipOption("messageHistory", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// trace
docComment = findJavaDoc(elementUtils, null, "handleFault", classElement, true);
ep = new EipOption("handleFault", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// delayer
docComment = findJavaDoc(elementUtils, null, "delayer", classElement, true);
ep = new EipOption("delayer", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// autoStartup
docComment = findJavaDoc(elementUtils, null, "autoStartup", classElement, true);
ep = new EipOption("autoStartup", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// startupOrder
docComment = findJavaDoc(elementUtils, null, "startupOrder", classElement, true);
ep = new EipOption("startupOrder", "attribute", "java.lang.Integer", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// errorHandlerRef
docComment = findJavaDoc(elementUtils, null, "errorHandlerRef", classElement, true);
ep = new EipOption("errorHandlerRef", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// routePolicyRef
docComment = findJavaDoc(elementUtils, null, "routePolicyRef", classElement, true);
ep = new EipOption("routePolicyRef", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// shutdownRoute
Set<String> enums = new LinkedHashSet<String>();
enums.add("Default");
enums.add("Defer");
docComment = findJavaDoc(elementUtils, null, "shutdownRoute", classElement, true);
ep = new EipOption("shutdownRoute", "attribute", "org.apache.camel.ShutdownRoute", false, "", docComment, false, true, enums, false, null);
eipOptions.add(ep);
// shutdownRunningTask
enums = new LinkedHashSet<String>();
enums.add("CompleteCurrentTaskOnly");
enums.add("CompleteAllTasks");
docComment = findJavaDoc(elementUtils, null, "shutdownRunningTask", classElement, true);
ep = new EipOption("shutdownRunningTask", "attribute", "org.apache.camel.ShutdownRunningTask", false, "", docComment, false, true, enums, false, null);
eipOptions.add(ep);
// inputs
Set<String> oneOfTypes = new TreeSet<String>();
oneOfTypes.add("from");
docComment = findJavaDoc(elementUtils, null, "inputs", classElement, true);
ep = new EipOption("inputs", "element", "java.util.List<org.apache.camel.model.FromDefinition>", true, "", docComment, false, false, null, true, oneOfTypes);
eipOptions.add(ep);
// outputs
// gather oneOf which extends any of the output base classes
oneOfTypes = new TreeSet<String>();
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
for (String superclass : ONE_OF_OUTPUTS) {
findTypeElementChildren(roundEnv, children, superclass);
}
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
// remove some types which are not intended as an output in eips
oneOfTypes.remove("route");
docComment = findJavaDoc(elementUtils, null, "outputs", classElement, true);
ep = new EipOption("outputs", "element", "java.util.List<org.apache.camel.model.ProcessorDefinition<?>>", true, "", docComment, false, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
/**
* Special for process the OptionalIdentifiedDefinition
*/
private void processIdentified(RoundEnvironment roundEnv, TypeElement originalClassType, TypeElement classElement,
Set<EipOption> eipOptions, String prefix) {
Elements elementUtils = processingEnv.getElementUtils();
// id
String docComment = findJavaDoc(elementUtils, null, "id", classElement, true);
EipOption ep = new EipOption("id", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// description
docComment = findJavaDoc(elementUtils, null, "description", classElement, true);
ep = new EipOption("description", "element", "org.apache.camel.model.DescriptionDefinition", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
// lets skip custom id as it has no value for end users to configure
if (!skipUnwanted) {
// custom id
docComment = findJavaDoc(elementUtils, null, "customId", classElement, true);
ep = new EipOption("customId", "attribute", "java.lang.String", false, "", docComment, false, false, null, false, null);
eipOptions.add(ep);
}
}
/**
* Special for processing an @XmlElementRef expression field
*/
private void processExpression(RoundEnvironment roundEnv, XmlElementRef elementRef, VariableElement fieldElement,
String fieldName, Set<EipOption> eipOptions, String prefix) {
if ("expression".equals(fieldName)) {
String kind = "element";
String name = elementRef.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
// gather oneOf expression/predicates which uses language
Set<String> oneOfTypes = new TreeSet<String>();
TypeElement languages = findTypeElement(roundEnv, ONE_OF_LANGUAGES);
String superClassName = canonicalClassName(languages.toString());
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
findTypeElementChildren(roundEnv, children, superClassName);
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null;
EipOption ep = new EipOption(name, kind, fieldTypeName, true, "", "", deprecated, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
}
/**
* Special for processing an @XmlElementRef outputs field
*/
private void processOutputs(RoundEnvironment roundEnv, TypeElement originalClassType, XmlElementRef elementRef,
VariableElement fieldElement, String fieldName, Set<EipOption> eipOptions, String prefix) {
if ("outputs".equals(fieldName) && supportOutputs(originalClassType)) {
String kind = "element";
String name = elementRef.name();
if (isNullOrEmpty(name) || "##default".equals(name)) {
name = fieldName;
}
name = prefix + name;
TypeMirror fieldType = fieldElement.asType();
String fieldTypeName = fieldType.toString();
// gather oneOf which extends any of the output base classes
Set<String> oneOfTypes = new TreeSet<String>();
// find all classes that has that superClassName
Set<TypeElement> children = new LinkedHashSet<TypeElement>();
for (String superclass : ONE_OF_OUTPUTS) {
findTypeElementChildren(roundEnv, children, superclass);
}
for (TypeElement child : children) {
XmlRootElement rootElement = child.getAnnotation(XmlRootElement.class);
if (rootElement != null) {
String childName = rootElement.name();
if (childName != null) {
oneOfTypes.add(childName);
}
}
}
// remove some types which are not intended as an output in eips
oneOfTypes.remove("route");
EipOption ep = new EipOption(name, kind, fieldTypeName, true, "", "", false, false, null, true, oneOfTypes);
eipOptions.add(ep);
}
}
/**
* Whether the class supports outputs.
* <p/>
* There are some classes which does not support outputs, even though they have a outputs element.
*/
private boolean supportOutputs(TypeElement classElement) {
String superclass = canonicalClassName(classElement.getSuperclass().toString());
return !"org.apache.camel.model.NoOutputExpressionNode".equals(superclass);
}
private static final class EipModel {
private String name;
private String javaType;
private String label;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJavaType() {
return javaType;
}
public void setJavaType(String javaType) {
this.javaType = javaType;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
private static final class EipOption {
private String name;
private String kind;
private String type;
private boolean required;
private String defaultValue;
private String documentation;
private boolean deprecated;
private boolean enumType;
private Set<String> enums;
private boolean oneOf;
private Set<String> oneOfTypes;
private EipOption(String name, String kind, String type, boolean required, String defaultValue, String documentation, boolean deprecated,
boolean enumType, Set<String> enums, boolean oneOf, Set<String> oneOfTypes) {
this.name = name;
this.kind = kind;
this.type = type;
this.required = required;
this.defaultValue = defaultValue;
this.documentation = documentation;
this.deprecated = deprecated;
this.enumType = enumType;
this.enums = enums;
this.oneOf = oneOf;
this.oneOfTypes = oneOfTypes;
}
public String getName() {
return name;
}
public String getKind() {
return kind;
}
public String getType() {
return type;
}
public boolean isRequired() {
return required;
}
public String getDefaultValue() {
return defaultValue;
}
public String getDocumentation() {
return documentation;
}
public boolean isDeprecated() {
return deprecated;
}
public boolean isEnumType() {
return enumType;
}
public Set<String> getEnums() {
return enums;
}
public boolean isOneOf() {
return oneOf;
}
public Set<String> getOneOfTypes() {
return oneOfTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EipOption that = (EipOption) o;
if (!name.equals(that.name)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return name.hashCode();
}
}
}
|
CAMEL-8251: eip model lets include a title which we later can improve or manually configured.
|
tooling/apt/src/main/java/org/apache/camel/tools/apt/EipAnnotationProcessor.java
|
CAMEL-8251: eip model lets include a title which we later can improve or manually configured.
|
<ide><path>ooling/apt/src/main/java/org/apache/camel/tools/apt/EipAnnotationProcessor.java
<ide> buffer.append("\n \"model\": {");
<ide> buffer.append("\n \"kind\": \"").append("model").append("\",");
<ide> buffer.append("\n \"name\": \"").append(eipModel.getName()).append("\",");
<add> buffer.append("\n \"title\": \"").append(asTitle(eipModel.getName())).append("\",");
<ide> buffer.append("\n \"description\": \"").append(safeNull(eipModel.getDescription())).append("\",");
<ide> buffer.append("\n \"javaType\": \"").append(eipModel.getJavaType()).append("\",");
<ide> buffer.append("\n \"label\": \"").append(safeNull(eipModel.getLabel())).append("\",");
<ide> return !"org.apache.camel.model.NoOutputExpressionNode".equals(superclass);
<ide> }
<ide>
<add> /**
<add> * Capitializes the name as a title
<add> *
<add> * @param name the name
<add> * @return as a title
<add> */
<add> private static String asTitle(String name) {
<add> StringBuilder sb = new StringBuilder();
<add> for (char c : name.toCharArray()) {
<add> boolean upper = Character.isUpperCase(c);
<add> boolean first = sb.length() == 0;
<add> if (first) {
<add> sb.append(Character.toUpperCase(c));
<add> } else if (upper) {
<add> sb.append(' ');
<add> sb.append(c);
<add> } else {
<add> sb.append(Character.toLowerCase(c));
<add> }
<add> }
<add> return sb.toString().trim();
<add> }
<add>
<ide> private static final class EipModel {
<ide>
<ide> private String name;
|
|
Java
|
apache-2.0
|
d952f1adaea3ae1db16a77fe2f40f0892672a680
| 0 |
nelenkov/wwwjdic,nelenkov/wwwjdic,nelenkov/wwwjdic
|
package org.nick.wwwjdic;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.nick.wwwjdic.history.HistoryDbHelper;
import org.nick.wwwjdic.model.WwwjdicEntry;
import org.nick.wwwjdic.utils.DictUtils;
import org.nick.wwwjdic.utils.IntentSpan;
import org.nick.wwwjdic.utils.Pair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.ClipboardManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
@SuppressWarnings("deprecation")
public abstract class DetailFragment extends SherlockFragment implements
OnCheckedChangeListener, OnLongClickListener,
TextToSpeech.OnInitListener {
protected static final Pattern CROSS_REF_PATTERN = Pattern
.compile("^.*\\(See (\\S+)\\).*$");
protected static final int ITEM_ID_HOME = 0;
private static final String TAG = DetailFragment.class.getSimpleName();
private static final int TTS_DATA_CHECK_CODE = 0;
private static final boolean IS_FROYO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
private static Method tts_getDefaultEngine;
private static Method tts_setEngineByPackageName;
static {
try {
tts_getDefaultEngine = TextToSpeech.class.getMethod(
"getDefaultEngine", (Class[]) null);
tts_setEngineByPackageName = TextToSpeech.class.getMethod(
"setEngineByPackageName", new Class[] { String.class });
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
}
}
protected HistoryDbHelper db;
protected WwwjdicEntry wwwjdicEntry;
protected boolean isFavorite;
protected TextToSpeech tts;
protected TextToSpeech jpTts;
private String jpTtsEnginePackageName;
protected DetailFragment() {
}
protected void addToFavorites() {
long favoriteId = db.addFavorite(wwwjdicEntry);
wwwjdicEntry.setId(favoriteId);
}
protected void removeFromFavorites() {
db.deleteFavorite(wwwjdicEntry.getId());
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
db = HistoryDbHelper.getInstance(getActivity());
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
jpTtsEnginePackageName = WwwjdicPreferences
.getJpTtsEnginePackage(activity);
}
@Override
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.shutdown();
}
if (jpTts != null) {
jpTts.shutdown();
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
addToFavorites();
} else {
removeFromFavorites();
}
}
@Override
public boolean onLongClick(View v) {
copy();
return true;
}
protected WwwjdicApplication getApp() {
return WwwjdicApplication.getInstance();
}
protected void makeClickable(TextView textView, int start, int end,
Intent intent) {
SpannableString str = SpannableString.valueOf(textView.getText());
str.setSpan(new IntentSpan(getActivity(), intent), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(str);
textView.setLinkTextColor(Color.WHITE);
MovementMethod m = textView.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (textView.getLinksClickable()) {
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
@Override
public void onInit(int status) {
// TODO should check which engine failed?
if (status != TextToSpeech.SUCCESS) {
hideTtsButtons();
toggleJpTtsButtons(false);
return;
}
if (jpTts != null && IS_FROYO) {
try {
String defaultEngine = (String) tts_getDefaultEngine.invoke(
jpTts, (Object[]) null);
if (!defaultEngine.equals(jpTtsEnginePackageName)) {
int rc = (Integer) tts_setEngineByPackageName.invoke(jpTts,
new Object[] { jpTtsEnginePackageName });
if (rc == TextToSpeech.ERROR) {
Log.w(TAG, jpTtsEnginePackageName + " not available?");
jpTts.shutdown();
jpTts = null;
toggleJpTtsButtons(false);
return;
}
}
jpTts.setLanguage(Locale.JAPAN);
toggleJpTtsButtons(true);
} catch (InvocationTargetException e) {
Log.e(TAG, "error calling by reflection: " + e.getMessage());
toggleJpTtsButtons(false);
} catch (IllegalAccessException e) {
Log.e(TAG, "error calling by reflection: " + e.getMessage());
toggleJpTtsButtons(false);
}
}
if (tts != null) {
Locale locale = getSpeechLocale();
if (locale == null) {
Log.w(TAG, "TTS locale " + locale + "not recognized");
hideTtsButtons();
return;
}
if (tts.isLanguageAvailable(locale) != TextToSpeech.LANG_MISSING_DATA
&& tts.isLanguageAvailable(locale) != TextToSpeech.LANG_NOT_SUPPORTED) {
tts.setLanguage(getSpeechLocale());
showTtsButtons();
} else {
Log.w(TAG, "TTS locale " + locale + " not available");
hideTtsButtons();
}
}
}
protected abstract void showTtsButtons();
protected abstract void hideTtsButtons();
protected abstract void toggleJpTtsButtons(boolean show);
protected Pair<LinearLayout, TextView> createMeaningTextView(
final Context ctx, String meaning) {
return createMeaningTextView(ctx, meaning, true);
}
protected Pair<LinearLayout, TextView> createMeaningTextView(
final Context ctx, String meaning, boolean enableTts) {
LayoutInflater inflater = LayoutInflater.from(ctx);
LinearLayout translationLayout = (LinearLayout) inflater.inflate(
R.layout.translation_item, null);
final TextView translationText = (TextView) translationLayout
.findViewById(R.id.translation_text);
translationText.setText(meaning);
Button speakButton = (Button) translationLayout
.findViewById(R.id.speak_button);
if (enableTts) {
speakButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String toSpeak = DictUtils.stripWwwjdicTags(ctx,
translationText.getText().toString());
if (tts != null) {
tts.speak(toSpeak, TextToSpeech.QUEUE_ADD, null);
}
}
});
} else {
translationLayout.removeView(speakButton);
}
Pair<LinearLayout, TextView> result = new Pair<LinearLayout, TextView>(
translationLayout, translationText);
return result;
}
protected abstract Locale getSpeechLocale();
protected void checkTtsAvailability() {
PackageManager pm = getActivity().getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(jpTtsEnginePackageName, 0);
if (pi != null) {
jpTts = new TextToSpeech(getActivity(), this);
}
} catch (NameNotFoundException e) {
Log.w(TAG, jpTtsEnginePackageName + " not found");
}
if (!isIntentAvailable(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA)) {
return;
}
Intent checkIntent = new Intent(
TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, TTS_DATA_CHECK_CODE);
}
private boolean isIntentAvailable(String action) {
PackageManager packageManager = getActivity().getPackageManager();
Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(getActivity(), this);
} else {
if (WwwjdicPreferences.wantsTts(getActivity())) {
Dialog dialog = createInstallTtsDataDialog();
dialog.show();
} else {
hideTtsButtons();
}
}
}
}
public Dialog createInstallTtsDataDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setMessage(R.string.install_tts_data_message)
.setTitle(R.string.install_tts_data_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
WwwjdicPreferences.setWantsTts(getActivity(),
true);
Intent installIntent = new Intent(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
dialog.dismiss();
startActivity(installIntent);
}
})
.setNegativeButton(R.string.not_now,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
hideTtsButtons();
dialog.dismiss();
}
})
.setNeutralButton(R.string.dont_ask_again,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
hideTtsButtons();
WwwjdicPreferences.setWantsTts(getActivity(),
false);
dialog.dismiss();
}
});
return builder.create();
}
protected void copy() {
ClipboardManager cm = (ClipboardManager) getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(wwwjdicEntry.getHeadword());
String messageTemplate = getResources().getString(
R.string.copied_to_clipboard);
Toast.makeText(getActivity(),
String.format(messageTemplate, wwwjdicEntry.getHeadword()),
Toast.LENGTH_SHORT).show();
}
protected void share() {
Intent shareIntent = createShareIntent();
getActivity().startActivity(shareIntent);
}
protected Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
String str = wwwjdicEntry.getHeadword() + " "
+ wwwjdicEntry.getDetailString();
shareIntent.putExtra(Intent.EXTRA_TEXT, str);
return shareIntent;
}
}
|
wwwjdic/src/org/nick/wwwjdic/DetailFragment.java
|
package org.nick.wwwjdic;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.nick.wwwjdic.history.HistoryDbHelper;
import org.nick.wwwjdic.model.WwwjdicEntry;
import org.nick.wwwjdic.utils.DictUtils;
import org.nick.wwwjdic.utils.IntentSpan;
import org.nick.wwwjdic.utils.Pair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.ClipboardManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
@SuppressWarnings("deprecation")
public abstract class DetailFragment extends SherlockFragment implements
OnCheckedChangeListener, OnLongClickListener,
TextToSpeech.OnInitListener {
protected static final Pattern CROSS_REF_PATTERN = Pattern
.compile("^.*\\(See (\\S+)\\).*$");
protected static final int ITEM_ID_HOME = 0;
private static final String TAG = DetailFragment.class.getSimpleName();
private static final int TTS_DATA_CHECK_CODE = 0;
private static final boolean IS_FROYO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
private static Method tts_getDefaultEngine;
private static Method tts_setEngineByPackageName;
static {
try {
tts_getDefaultEngine = TextToSpeech.class.getMethod(
"getDefaultEngine", (Class[]) null);
tts_setEngineByPackageName = TextToSpeech.class.getMethod(
"setEngineByPackageName", new Class[] { String.class });
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
}
}
protected HistoryDbHelper db;
protected WwwjdicEntry wwwjdicEntry;
protected boolean isFavorite;
protected TextToSpeech tts;
protected TextToSpeech jpTts;
private String jpTtsEnginePackageName;
protected DetailFragment() {
}
protected void addToFavorites() {
long favoriteId = db.addFavorite(wwwjdicEntry);
wwwjdicEntry.setId(favoriteId);
}
protected void removeFromFavorites() {
db.deleteFavorite(wwwjdicEntry.getId());
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
db = HistoryDbHelper.getInstance(getActivity());
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
jpTtsEnginePackageName = WwwjdicPreferences
.getJpTtsEnginePackage(activity);
}
@Override
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.shutdown();
}
if (jpTts != null) {
jpTts.shutdown();
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
addToFavorites();
} else {
removeFromFavorites();
}
}
@Override
public boolean onLongClick(View v) {
copy();
return true;
}
protected WwwjdicApplication getApp() {
return WwwjdicApplication.getInstance();
}
protected void makeClickable(TextView textView, int start, int end,
Intent intent) {
SpannableString str = SpannableString.valueOf(textView.getText());
str.setSpan(new IntentSpan(getActivity(), intent), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(str);
textView.setLinkTextColor(Color.WHITE);
MovementMethod m = textView.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (textView.getLinksClickable()) {
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
@Override
public void onInit(int status) {
// TODO should check which engine failed?
if (status != TextToSpeech.SUCCESS) {
hideTtsButtons();
toggleJpTtsButtons(false);
return;
}
if (jpTts != null && IS_FROYO) {
try {
String defaultEngine = (String) tts_getDefaultEngine.invoke(
jpTts, (Object[]) null);
if (!defaultEngine.equals(jpTtsEnginePackageName)) {
int rc = (Integer) tts_setEngineByPackageName.invoke(jpTts,
new Object[] { jpTtsEnginePackageName });
if (rc == TextToSpeech.ERROR) {
Log.w(TAG, jpTtsEnginePackageName + " not available?");
jpTts.shutdown();
jpTts = null;
toggleJpTtsButtons(false);
return;
}
}
jpTts.setLanguage(Locale.JAPAN);
toggleJpTtsButtons(true);
} catch (InvocationTargetException e) {
Log.e(TAG, "error calling by reflection: " + e.getMessage());
toggleJpTtsButtons(false);
} catch (IllegalAccessException e) {
Log.e(TAG, "error calling by reflection: " + e.getMessage());
toggleJpTtsButtons(false);
}
}
if (tts != null) {
Locale locale = getSpeechLocale();
if (locale == null) {
Log.w(TAG, "TTS locale " + locale + "not recognized");
hideTtsButtons();
return;
}
if (tts.isLanguageAvailable(locale) != TextToSpeech.LANG_MISSING_DATA
&& tts.isLanguageAvailable(locale) != TextToSpeech.LANG_NOT_SUPPORTED) {
tts.setLanguage(getSpeechLocale());
showTtsButtons();
} else {
Log.w(TAG, "TTS locale " + locale + " not available");
hideTtsButtons();
}
}
}
protected abstract void showTtsButtons();
protected abstract void hideTtsButtons();
protected abstract void toggleJpTtsButtons(boolean show);
protected Pair<LinearLayout, TextView> createMeaningTextView(
final Context ctx, String meaning) {
return createMeaningTextView(ctx, meaning, true);
}
protected Pair<LinearLayout, TextView> createMeaningTextView(
final Context ctx, String meaning, boolean enableTts) {
LayoutInflater inflater = LayoutInflater.from(ctx);
LinearLayout translationLayout = (LinearLayout) inflater.inflate(
R.layout.translation_item, null);
final TextView translationText = (TextView) translationLayout
.findViewById(R.id.translation_text);
translationText.setText(meaning);
Button speakButton = (Button) translationLayout
.findViewById(R.id.speak_button);
if (enableTts) {
speakButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String toSpeak = DictUtils.stripWwwjdicTags(ctx,
translationText.getText().toString());
if (tts != null) {
tts.speak(toSpeak, TextToSpeech.QUEUE_ADD, null);
}
}
});
} else {
translationLayout.removeView(speakButton);
}
Pair<LinearLayout, TextView> result = new Pair<LinearLayout, TextView>(
translationLayout, translationText);
return result;
}
protected abstract Locale getSpeechLocale();
protected void checkTtsAvailability() {
PackageManager pm = getActivity().getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(jpTtsEnginePackageName, 0);
if (pi != null) {
jpTts = new TextToSpeech(getActivity(), this);
}
} catch (NameNotFoundException e) {
Log.w(TAG, jpTtsEnginePackageName + " not found");
}
if (!isIntentAvailable(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA)) {
return;
}
Intent checkIntent = new Intent(
TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, TTS_DATA_CHECK_CODE);
}
private boolean isIntentAvailable(String action) {
PackageManager packageManager = getActivity().getPackageManager();
Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(getActivity(), this);
} else {
if (WwwjdicPreferences.wantsTts(getActivity())) {
Dialog dialog = createInstallTtsDataDialog();
dialog.show();
} else {
hideTtsButtons();
}
}
}
}
public Dialog createInstallTtsDataDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setMessage(R.string.install_tts_data_message)
.setTitle(R.string.install_tts_data_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
WwwjdicPreferences.setWantsTts(getActivity(),
true);
Intent installIntent = new Intent(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
dialog.dismiss();
startActivity(installIntent);
}
})
.setNegativeButton(R.string.not_now,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
hideTtsButtons();
dialog.dismiss();
}
})
.setNeutralButton(R.string.dont_ask_again,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
hideTtsButtons();
WwwjdicPreferences.setWantsTts(getActivity(),
false);
dialog.dismiss();
}
});
return builder.create();
}
protected void copy() {
ClipboardManager cm = (ClipboardManager) getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(wwwjdicEntry.getHeadword());
String messageTemplate = getResources().getString(
R.string.copied_to_clipboard);
Toast.makeText(getActivity(),
String.format(messageTemplate, wwwjdicEntry.getHeadword()),
Toast.LENGTH_SHORT).show();
}
protected void share() {
Intent shareIntent = createShareIntent();
getActivity().startActivity(shareIntent);
}
protected Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
String str = wwwjdicEntry.getDetailString();
shareIntent.putExtra(Intent.EXTRA_TEXT, str);
return shareIntent;
}
}
|
include headword in shared text
|
wwwjdic/src/org/nick/wwwjdic/DetailFragment.java
|
include headword in shared text
|
<ide><path>wwjdic/src/org/nick/wwwjdic/DetailFragment.java
<ide> Intent shareIntent = new Intent(Intent.ACTION_SEND);
<ide> shareIntent.setType("text/plain");
<ide> shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
<del> String str = wwwjdicEntry.getDetailString();
<add> String str = wwwjdicEntry.getHeadword() + " "
<add> + wwwjdicEntry.getDetailString();
<ide> shareIntent.putExtra(Intent.EXTRA_TEXT, str);
<ide>
<ide> return shareIntent;
|
|
Java
|
mit
|
619d852d3a69f7c26a7367cda56dadce3a7b85c3
| 0 |
axsy-dev/react-native-sqlcipher-storage,axsy-dev/react-native-sqlcipher-storage,axsy-dev/react-native-sqlcipher-storage,andpor/react-native-sqlite-storage,andpor/react-native-sqlite-storage,axsy-dev/react-native-sqlcipher-storage,axsy-dev/react-native-sqlcipher-storage,andpor/react-native-sqlite-storage,axsy-dev/react-native-sqlcipher-storage,axsy-dev/react-native-sqlcipher-storage,andpor/react-native-sqlite-storage
|
/**
* Written by Andrzej Porebski Nov 14/2015
*
* Copyright (c) 2015, Andrzej Porebski
*/
package org.pgsqlite;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
public abstract class SQLitePluginConverter {
static JSONObject reactToJSON(ReadableMap readableMap) throws JSONException {
JSONObject jsonObject = new JSONObject();
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
while(iterator.hasNextKey()){
String key = iterator.nextKey();
ReadableType valueType = readableMap.getType(key);
switch (valueType){
case Null:
jsonObject.put(key,JSONObject.NULL);
break;
case Boolean:
jsonObject.put(key, readableMap.getBoolean(key));
break;
case Number:
jsonObject.put(key, readableMap.getInt(key));
break;
case String:
jsonObject.put(key, readableMap.getString(key));
break;
case Map:
jsonObject.put(key, reactToJSON(readableMap.getMap(key)));
break;
case Array:
jsonObject.put(key, reactToJSON(readableMap.getArray(key)));
break;
}
}
return jsonObject;
}
static JSONArray reactToJSON(ReadableArray readableArray) throws JSONException {
JSONArray jsonArray = new JSONArray();
for(int i=0; i < readableArray.size(); i++) {
ReadableType valueType = readableArray.getType(i);
switch (valueType){
case Null:
jsonArray.put(JSONObject.NULL);
break;
case Boolean:
jsonArray.put(readableArray.getBoolean(i));
break;
case Number:
jsonArray.put(readableArray.getInt(i));
break;
case String:
jsonArray.put(readableArray.getString(i));
break;
case Map:
jsonArray.put(reactToJSON(readableArray.getMap(i)));
break;
case Array:
jsonArray.put(reactToJSON(readableArray.getArray(i)));
break;
}
}
return jsonArray;
}
static WritableMap jsonToReact(JSONObject jsonObject) throws JSONException {
WritableMap writableMap = Arguments.createMap();
Iterator iterator = jsonObject.keys();
while(iterator.hasNext()) {
String key = (String) iterator.next();
Object value = jsonObject.get(key);
if (value instanceof Float || value instanceof Double) {
writableMap.putDouble(key, jsonObject.getDouble(key));
} else if (value instanceof Number) {
writableMap.putInt(key, jsonObject.getInt(key));
} else if (value instanceof String) {
writableMap.putString(key, jsonObject.getString(key));
} else if (value instanceof JSONObject) {
writableMap.putMap(key,jsonToReact(jsonObject.getJSONObject(key)));
} else if (value instanceof JSONArray){
writableMap.putArray(key, jsonToReact(jsonObject.getJSONArray(key)));
} else if (value == JSONObject.NULL){
writableMap.putNull(key);
}
}
return writableMap;
}
static WritableArray jsonToReact(JSONArray jsonArray) throws JSONException {
WritableArray writableArray = Arguments.createArray();
for(int i=0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof Float || value instanceof Double) {
writableArray.pushDouble(jsonArray.getDouble(i));
} else if (value instanceof Number) {
writableArray.pushInt(jsonArray.getInt(i));
} else if (value instanceof String) {
writableArray.pushString(jsonArray.getString(i));
} else if (value instanceof JSONObject) {
writableArray.pushMap(jsonToReact(jsonArray.getJSONObject(i)));
} else if (value instanceof JSONArray){
writableArray.pushArray(jsonToReact(jsonArray.getJSONArray(i)));
} else if (value == JSONObject.NULL){
writableArray.pushNull();
}
}
return writableArray;
}
}
|
src/android/src/main/java/org/pgsqlite/SQLitePluginConverter.java
|
/**
* Written by Andrzej Porebski Nov 14/2015
*
* Copyright (c) 2015, Andrzej Porebski
*/
package org.pgsqlite;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySeyIterator;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
public abstract class SQLitePluginConverter {
static JSONObject reactToJSON(ReadableMap readableMap) throws JSONException {
JSONObject jsonObject = new JSONObject();
ReadableMapKeySeyIterator iterator = readableMap.keySetIterator();
while(iterator.hasNextKey()){
String key = iterator.nextKey();
ReadableType valueType = readableMap.getType(key);
switch (valueType){
case Null:
jsonObject.put(key,JSONObject.NULL);
break;
case Boolean:
jsonObject.put(key, readableMap.getBoolean(key));
break;
case Number:
jsonObject.put(key, readableMap.getInt(key));
break;
case String:
jsonObject.put(key, readableMap.getString(key));
break;
case Map:
jsonObject.put(key, reactToJSON(readableMap.getMap(key)));
break;
case Array:
jsonObject.put(key, reactToJSON(readableMap.getArray(key)));
break;
}
}
return jsonObject;
}
static JSONArray reactToJSON(ReadableArray readableArray) throws JSONException {
JSONArray jsonArray = new JSONArray();
for(int i=0; i < readableArray.size(); i++) {
ReadableType valueType = readableArray.getType(i);
switch (valueType){
case Null:
jsonArray.put(JSONObject.NULL);
break;
case Boolean:
jsonArray.put(readableArray.getBoolean(i));
break;
case Number:
jsonArray.put(readableArray.getInt(i));
break;
case String:
jsonArray.put(readableArray.getString(i));
break;
case Map:
jsonArray.put(reactToJSON(readableArray.getMap(i)));
break;
case Array:
jsonArray.put(reactToJSON(readableArray.getArray(i)));
break;
}
}
return jsonArray;
}
static WritableMap jsonToReact(JSONObject jsonObject) throws JSONException {
WritableMap writableMap = Arguments.createMap();
Iterator iterator = jsonObject.keys();
while(iterator.hasNext()) {
String key = (String) iterator.next();
Object value = jsonObject.get(key);
if (value instanceof Float || value instanceof Double) {
writableMap.putDouble(key, jsonObject.getDouble(key));
} else if (value instanceof Number) {
writableMap.putInt(key, jsonObject.getInt(key));
} else if (value instanceof String) {
writableMap.putString(key, jsonObject.getString(key));
} else if (value instanceof JSONObject) {
writableMap.putMap(key,jsonToReact(jsonObject.getJSONObject(key)));
} else if (value instanceof JSONArray){
writableMap.putArray(key, jsonToReact(jsonObject.getJSONArray(key)));
} else if (value == JSONObject.NULL){
writableMap.putNull(key);
}
}
return writableMap;
}
static WritableArray jsonToReact(JSONArray jsonArray) throws JSONException {
WritableArray writableArray = Arguments.createArray();
for(int i=0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof Float || value instanceof Double) {
writableArray.pushDouble(jsonArray.getDouble(i));
} else if (value instanceof Number) {
writableArray.pushInt(jsonArray.getInt(i));
} else if (value instanceof String) {
writableArray.pushString(jsonArray.getString(i));
} else if (value instanceof JSONObject) {
writableArray.pushMap(jsonToReact(jsonArray.getJSONObject(i)));
} else if (value instanceof JSONArray){
writableArray.pushArray(jsonToReact(jsonArray.getJSONArray(i)));
} else if (value == JSONObject.NULL){
writableArray.pushNull();
}
}
return writableArray;
}
}
|
Update SQLitePluginConverter.java
Fix https://github.com/andpor/react-native-sqlite-storage/issues/3
|
src/android/src/main/java/org/pgsqlite/SQLitePluginConverter.java
|
Update SQLitePluginConverter.java
|
<ide><path>rc/android/src/main/java/org/pgsqlite/SQLitePluginConverter.java
<ide> import com.facebook.react.bridge.Arguments;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<del>import com.facebook.react.bridge.ReadableMapKeySeyIterator;
<add>import com.facebook.react.bridge.ReadableMapKeySetIterator;
<ide> import com.facebook.react.bridge.ReadableType;
<ide> import com.facebook.react.bridge.WritableArray;
<ide> import com.facebook.react.bridge.WritableMap;
<ide> public abstract class SQLitePluginConverter {
<ide> static JSONObject reactToJSON(ReadableMap readableMap) throws JSONException {
<ide> JSONObject jsonObject = new JSONObject();
<del> ReadableMapKeySeyIterator iterator = readableMap.keySetIterator();
<add> ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
<ide> while(iterator.hasNextKey()){
<ide> String key = iterator.nextKey();
<ide> ReadableType valueType = readableMap.getType(key);
|
|
Java
|
mit
|
d7b5bda72e045ba8a4bd458613904a5ce7b37c84
| 0 |
yidongnan/grpc-spring-boot-starter,yidongnan/grpc-spring-boot-starter,yidongnan/grpc-spring-boot-starter
|
/*
* Copyright (c) 2016-2021 Michael Zhang <[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 net.devh.boot.grpc.server.serverfactory;
import static java.util.Objects.requireNonNull;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.util.unit.DataSize;
import com.google.common.collect.Lists;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.config.GrpcServerProperties;
import net.devh.boot.grpc.server.service.GrpcServiceDefinition;
/**
* Abstract factory for grpc servers.
*
* @param <T> The type of builder used by this factory.
* @author Michael ([email protected])
* @author Daniel Theuke ([email protected])
* @since 5/17/16
*/
@Slf4j
public abstract class AbstractGrpcServerFactory<T extends ServerBuilder<T>> implements GrpcServerFactory {
private final List<GrpcServiceDefinition> serviceList = Lists.newLinkedList();
protected final GrpcServerProperties properties;
protected final List<GrpcServerConfigurer> serverConfigurers;
/**
* Creates a new server factory with the given properties.
*
* @param properties The properties used to configure the server.
* @param serverConfigurers The server configurers to use. Can be empty.
*/
protected AbstractGrpcServerFactory(final GrpcServerProperties properties,
final List<GrpcServerConfigurer> serverConfigurers) {
this.properties = requireNonNull(properties, "properties");
this.serverConfigurers = requireNonNull(serverConfigurers, "serverConfigurers");
}
@Override
public Server createServer() {
final T builder = newServerBuilder();
configure(builder);
return builder.build();
}
/**
* Creates a new server builder.
*
* @return The newly created server builder.
*/
protected abstract T newServerBuilder();
/**
* Configures the given server builder. This method can be overwritten to add features that are not yet supported by
* this library or use a {@link GrpcServerConfigurer} instead.
*
* @param builder The server builder to configure.
*/
protected void configure(final T builder) {
configureServices(builder);
configureKeepAlive(builder);
configureConnectionLimits(builder);
configureSecurity(builder);
configureLimits(builder);
for (final GrpcServerConfigurer serverConfigurer : this.serverConfigurers) {
serverConfigurer.accept(builder);
}
}
/**
* Configures the services that should be served by the server.
*
* @param builder The server builder to configure.
*/
protected void configureServices(final T builder) {
final Set<String> serviceNames = new LinkedHashSet<>();
for (final GrpcServiceDefinition service : this.serviceList) {
final String serviceName = service.getDefinition().getServiceDescriptor().getName();
if (!serviceNames.add(serviceName)) {
throw new IllegalStateException("Found duplicate service implementation: " + serviceName);
}
log.info("Registered gRPC service: " + serviceName + ", bean: " + service.getBeanName() + ", class: "
+ service.getBeanClazz().getName());
builder.addService(service.getDefinition());
}
}
/**
* Configures the keep alive options that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureKeepAlive(final T builder) {
if (this.properties.isEnableKeepAlive()) {
throw new IllegalStateException("KeepAlive is enabled but this implementation does not support keepAlive!");
}
}
/**
* Configures the keep alive options that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureConnectionLimits(final T builder) {
if (this.properties.getMaxConnectionIdle() != null) {
throw new IllegalStateException(
"MaxConnectionIdle is set but this implementation does not support maxConnectionIdle!");
}
if (this.properties.getMaxConnectionAge() != null) {
throw new IllegalStateException(
"MaxConnectionAge is set but this implementation does not support maxConnectionAge!");
}
if (this.properties.getMaxConnectionAgeGrace() != null) {
throw new IllegalStateException(
"MaxConnectionAgeGrace is set but this implementation does not support maxConnectionAgeGrace!");
}
}
/**
* Configures the security options that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureSecurity(final T builder) {
if (this.properties.getSecurity().isEnabled()) {
throw new IllegalStateException("Security is enabled but this implementation does not support security!");
}
}
/**
* Configures limits such as max message sizes that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureLimits(final T builder) {
final DataSize maxInboundMessageSize = this.properties.getMaxInboundMessageSize();
if (maxInboundMessageSize != null) {
builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes());
}
final DataSize maxInboundMetadataSize = this.properties.getMaxInboundMetadataSize();
if (maxInboundMetadataSize != null) {
builder.maxInboundMetadataSize((int) maxInboundMetadataSize.toBytes());
}
}
@Override
public String getAddress() {
return this.properties.getAddress();
}
@Override
public int getPort() {
return this.properties.getPort();
}
@Override
public void addService(final GrpcServiceDefinition service) {
this.serviceList.add(service);
}
}
|
grpc-server-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/server/serverfactory/AbstractGrpcServerFactory.java
|
/*
* Copyright (c) 2016-2021 Michael Zhang <[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 net.devh.boot.grpc.server.serverfactory;
import static java.util.Objects.requireNonNull;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.util.unit.DataSize;
import com.google.common.collect.Lists;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.config.GrpcServerProperties;
import net.devh.boot.grpc.server.service.GrpcServiceDefinition;
/**
* Abstract factory for grpc servers.
*
* @param <T> The type of builder used by this factory.
* @author Michael ([email protected])
* @author Daniel Theuke ([email protected])
* @since 5/17/16
*/
@Slf4j
public abstract class AbstractGrpcServerFactory<T extends ServerBuilder<T>> implements GrpcServerFactory {
private final List<GrpcServiceDefinition> serviceList = Lists.newLinkedList();
protected final GrpcServerProperties properties;
protected final List<GrpcServerConfigurer> serverConfigurers;
/**
* Creates a new server factory with the given properties.
*
* @param properties The properties used to configure the server.
* @param serverConfigurers The server configurers to use. Can be empty.
*/
protected AbstractGrpcServerFactory(final GrpcServerProperties properties,
final List<GrpcServerConfigurer> serverConfigurers) {
this.properties = requireNonNull(properties, "properties");
this.serverConfigurers = requireNonNull(serverConfigurers, "serverConfigurers");
}
@Override
public Server createServer() {
final T builder = newServerBuilder();
configure(builder);
return builder.build();
}
/**
* Creates a new server builder.
*
* @return The newly created server builder.
*/
protected abstract T newServerBuilder();
/**
* Configures the given server builder. This method can be overwritten to add features that are not yet supported by
* this library or use a {@link GrpcServerConfigurer} instead.
*
* @param builder The server builder to configure.
*/
protected void configure(final T builder) {
configureServices(builder);
configureKeepAlive(builder);
configureConnectionLimits(builder);
configureSecurity(builder);
configureLimits(builder);
for (final GrpcServerConfigurer serverConfigurer : this.serverConfigurers) {
serverConfigurer.accept(builder);
}
}
/**
* Configures the services that should be served by the server.
*
* @param builder The server builder to configure.
*/
protected void configureServices(final T builder) {
final Set<String> serviceNames = new LinkedHashSet<>();
for (final GrpcServiceDefinition service : this.serviceList) {
final String serviceName = service.getDefinition().getServiceDescriptor().getName();
if (!serviceNames.add(serviceName)) {
throw new IllegalStateException("Found duplicate service implementation: " + serviceName);
}
log.info("Registered gRPC service: " + serviceName + ", bean: " + service.getBeanName() + ", class: "
+ service.getBeanClazz().getName());
builder.addService(service.getDefinition());
}
}
/**
* Configures the keep alive options that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureKeepAlive(final T builder) {
if (this.properties.isEnableKeepAlive()) {
throw new IllegalStateException("KeepAlive is enabled but this implementation does not support keepAlive!");
}
}
/**
* Configures the keep alive options that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureConnectionLimits(final T builder) {
if (this.properties.getMaxConnectionIdle() != null) {
throw new IllegalStateException(
"MaxConnectionIdle is set but this implementation does not support maxConnectionIdle!");
}
if (this.properties.getMaxConnectionAge() != null) {
throw new IllegalStateException(
"MaxConnectionAge is set but this implementation does not support maxConnectionAge!");
}
if (this.properties.getMaxConnectionAgeGrace() != null) {
throw new IllegalStateException(
"MaxConnectionAgeGrace is set but this implementation does not support maxConnectionAgeGrace!");
}
}
/**
* Configures the security options that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureSecurity(final T builder) {
if (this.properties.getSecurity().isEnabled()) {
throw new IllegalStateException("Security is enabled but this implementation does not support security!");
}
}
/**
* Configures limits such as max message sizes that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureLimits(final T builder) {
final DataSize maxInboundMessageSize = this.properties.getMaxInboundMessageSize();
if (maxInboundMessageSize != null) {
builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes());
}
final DataSize maxInboundMetadataSize = this.properties.getMaxInboundMetadataSize();
if (maxInboundMetadataSize != null) {
builder.maxInboundMetadataSize((int) maxInboundMetadataSize.toBytes());
}
}
@Override
public String getAddress() {
return this.properties.getAddress();
}
@Override
public int getPort() {
return this.properties.getPort();
}
@Override
public void addService(final GrpcServiceDefinition service) {
this.serviceList.add(service);
}
}
|
Fix checkstyle issue in AbstractGrpcServerFactory
|
grpc-server-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/server/serverfactory/AbstractGrpcServerFactory.java
|
Fix checkstyle issue in AbstractGrpcServerFactory
|
<ide><path>rpc-server-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/server/serverfactory/AbstractGrpcServerFactory.java
<ide> protected void configureConnectionLimits(final T builder) {
<ide> if (this.properties.getMaxConnectionIdle() != null) {
<ide> throw new IllegalStateException(
<del> "MaxConnectionIdle is set but this implementation does not support maxConnectionIdle!");
<add> "MaxConnectionIdle is set but this implementation does not support maxConnectionIdle!");
<ide> }
<ide> if (this.properties.getMaxConnectionAge() != null) {
<ide> throw new IllegalStateException(
<del> "MaxConnectionAge is set but this implementation does not support maxConnectionAge!");
<add> "MaxConnectionAge is set but this implementation does not support maxConnectionAge!");
<ide> }
<ide> if (this.properties.getMaxConnectionAgeGrace() != null) {
<ide> throw new IllegalStateException(
<del> "MaxConnectionAgeGrace is set but this implementation does not support maxConnectionAgeGrace!");
<add> "MaxConnectionAgeGrace is set but this implementation does not support maxConnectionAgeGrace!");
<ide> }
<ide> }
<ide>
|
|
JavaScript
|
mit
|
5bc21513ec9e76d79f4651ccec3674bef1585f17
| 0 |
SymSoftSolutions/CWS-Prototype,SymSoftSolutions/CWS-Prototype
|
var utils = require('../lib/utils');
var config = require('../config');
var dbUtils = require('../lib/dbUtils');
var middleware = require('../middleware');
var passport = require('passport');
var permission = require('permission');
exports.processMessages = processMessages;
exports.getMessageData = getMessageData;
/**
* Adds routes for handling user sent messages
* @param router
*/
function processMessages(router) {
router.get('/sendMessage', function(req, res, next) {
if(req.isAuthenticated()) {
res.render('forms/sendmessage');
}
});
/**
* Take user details, and if all entered in properly save user to the database.
* If something goes wrong we redirect back to the forms to try again, but with a message to the user too.
*/
router.post('/message', function(req, res, next) {
if(req.user && req.isAuthenticated()) {
/**
* Form must contain following components:
* subject IN message.subject
* message text IN message.text
* recipient IN message.recipientID
*/
var message = {};
message['fromID'] = req.user.userID;
message['subject'] = req.body.subject;
message['recipientID'] = parseInt(req.body.recipientID);
message['message'] = req.body.text;
message['hasRead'] = false;
var allFieldsExist = false;
if(message['subject'] != null &&
message['message'] != null &&
message['recipientID'] != null) {
allFieldsExist=true;
} else {
if(!allFieldsExist) {
req.flash('error', 'Required fields not filled');
}
req.flash('success', 'Message sent!');
res.redirect('/inbox');
return;
}
dbUtils.checkExist('users', {'userID': message['recipientID']}, function(err, recipientExists) {
if(err) {
res.render('501', {status: 501, url: req.url});
return;
}
if(recipientExists && allFieldsExist) {
dbUtils.addMessage(message).then(function() {
res.redirect('/sendMessage');
});
} else {
req.flash('error', 'Please enter a valid recipient');
res.redirect('/sendMessage');
}
});
}
else {
res.render('501', {status: 501, url: req.url});
}
});
}
function getMessageData(router) {
/**
* Gets message list for a specified user either sending or recieving messages
* Takes JSON request only
* Client should post JSON containing user's ID
*/
router.post('/getMessages', function(req, res) {
//var byRecipient = req.body.bySender; //If false, assumed to be asking for emails by sender - ones that were send by user
var byRecipient = true;
var userID = req.user.userID;
if(byRecipient) {
dbUtils.getRecievedMessages(userID).then(function(messageList) {
console.log('recieved request');
messageList = formatMessageData(messageList);
res.send(messageList);
});
} else {
dbUtils.getUserMessages(userID).then(function(messageList) {
messageList = formatMessageData(messageList);
res.send(messageList);
});
}
});
/**
* Gets address
*
*/
router.post('/getRelevantAddresses', function(req, res) {
});
}
function formatMessageData(messageList) {
var newList = [];
for(var index in messageList) {
var message = messageList[index];
var column_array =[message.fromID, message.subject, message.createdAt];
newList.push(column_array);
console.log(message);
}
console.log(newList);
return {"data": newList};
}
|
routes/privatemessage.js
|
var utils = require('../lib/utils');
var config = require('../config');
var dbUtils = require('../lib/dbUtils');
var middleware = require('../middleware');
var passport = require('passport');
var permission = require('permission');
exports.processMessages = processMessages;
exports.getMessageData = getMessageData;
/**
* Adds routes for handling user sent messages
* @param router
*/
function processMessages(router) {
router.get('/sendMessage', function(req, res, next) {
if(req.isAuthenticated()) {
res.render('forms/sendmessage');
}
});
/**
* Take user details, and if all entered in properly save user to the database.
* If something goes wrong we redirect back to the forms to try again, but with a message to the user too.
*/
router.post('/message', function(req, res, next) {
if(req.user && req.isAuthenticated()) {
/**
* Form must contain following components:
* subject IN message.subject
* message text IN message.text
* recipient IN message.recipientID
*/
var message = {};
message['fromID'] = req.user.userID;
message['subject'] = req.body.subject;
message['recipientID'] = parseInt(req.body.recipientID);
message['message'] = req.body.text;
message['hasRead'] = false;
console.log(message);
var allFieldsExist = false;
if(message['subject'] != null &&
message['message'] != null &&
message['recipientID'] != null) {
allFieldsExist=true;
} else {
if(!allFieldsExist) {
req.flash('error', 'Required fields not filled');
}
res.redirect('/sendMessage');
return;
}
dbUtils.checkExist('users', {'userID': message['recipientID']}, function(err, recipientExists) {
console.log('inside check exist callback');
if(err) {
res.render('501', {status: 501, url: req.url});
return;
}
if(recipientExists && allFieldsExist) {
dbUtils.addMessage(message).then(function() {
res.redirect('/sendMessage');
});
} else {
req.flash('error', 'Please enter a valid recipient');
res.redirect('/sendMessage');
}
});
}
else {
console.log('no user');
res.render('501', {status: 501, url: req.url});
}
});
}
function getMessageData(router) {
/**
* Gets message list for a specified user either sending or recieving messages
* Takes JSON request only
* Client should post JSON containing user's ID
*/
router.post('/getMessages', function(req, res) {
//var byRecipient = req.body.bySender; //If false, assumed to be asking for emails by sender - ones that were send by user
var byRecipient = true;
var userID = req.user.userID;
console.log('everything turns to ash');
if(byRecipient) {
dbUtils.getRecievedMessages(userID).then(function(messageList) {
res.send(messageList);
});
} else {
dbUtils.getUserMessages(userID).then(function(messageList) {
res.send(messageList);
});
}
});
/**
* Gets address
*
*/
router.post('/getRelevantAddresses', function(req, res) {
});
}
|
presents things in table correctly
|
routes/privatemessage.js
|
presents things in table correctly
|
<ide><path>outes/privatemessage.js
<ide> message['message'] = req.body.text;
<ide> message['hasRead'] = false;
<ide>
<del> console.log(message);
<ide> var allFieldsExist = false;
<ide> if(message['subject'] != null &&
<ide> message['message'] != null &&
<ide> if(!allFieldsExist) {
<ide> req.flash('error', 'Required fields not filled');
<ide> }
<del> res.redirect('/sendMessage');
<add> req.flash('success', 'Message sent!');
<add> res.redirect('/inbox');
<ide> return;
<ide> }
<ide>
<ide> dbUtils.checkExist('users', {'userID': message['recipientID']}, function(err, recipientExists) {
<del> console.log('inside check exist callback');
<ide>
<ide> if(err) {
<ide> res.render('501', {status: 501, url: req.url});
<ide> });
<ide> }
<ide> else {
<del> console.log('no user');
<ide> res.render('501', {status: 501, url: req.url});
<ide> }
<ide> });
<ide> //var byRecipient = req.body.bySender; //If false, assumed to be asking for emails by sender - ones that were send by user
<ide> var byRecipient = true;
<ide> var userID = req.user.userID;
<del>
<del> console.log('everything turns to ash');
<ide>
<ide> if(byRecipient) {
<ide> dbUtils.getRecievedMessages(userID).then(function(messageList) {
<add> console.log('recieved request');
<add> messageList = formatMessageData(messageList);
<ide> res.send(messageList);
<ide> });
<ide> } else {
<ide> dbUtils.getUserMessages(userID).then(function(messageList) {
<add> messageList = formatMessageData(messageList);
<ide> res.send(messageList);
<ide> });
<ide> }
<ide> router.post('/getRelevantAddresses', function(req, res) {
<ide> });
<ide> }
<add>
<add>function formatMessageData(messageList) {
<add> var newList = [];
<add> for(var index in messageList) {
<add> var message = messageList[index];
<add> var column_array =[message.fromID, message.subject, message.createdAt];
<add> newList.push(column_array);
<add> console.log(message);
<add> }
<add>
<add> console.log(newList);
<add> return {"data": newList};
<add>}
|
|
Java
|
mit
|
aeae24a34f4718a533ab6bb7d38bb88cad86594d
| 0 |
jimmylle/F16-lab04
|
package edu.ucsb.cs56.drawings.sswong.advanced;
import java.awt.geom.GeneralPath;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
/**
A Tree with Fruits
@author Simon Wong
@version for CS56, F16, UCSB
*/
public class TreeWithFruits extends Tree implements Shape{
/**
Constructor
@param x x coord of top left corner of tree
@param y y coord of top left corner of tree
@param leaves_radius radius of tree leaves
@param trunk_width width of trunk
@param trunk_height height of trunk
*/
public TreeWithFruits(double x, double y,
double leaves_radius,
double trunk_width,
double trunk_height)
{
// create the tree
super(x,y,leaves_radius,trunk_width,trunk_height);
// add three round fruits on the leaves, placed in a triangular fashion
Ellipse2D.Double fruit1 =
new Ellipse2D.Double(x+(0.667*leaves_radius),
y+(0.667*leaves_radius),
leaves_radius/5,
leaves_radius/5);
Ellipse2D.Double fruit2 =
new Ellipse2D.Double(x+leaves_radius,
y+(1.333*leaves_radius),
leaves_radius/5,
leaves_radius/5);
Ellipse2D.Double fruit3 =
new Ellipse2D.Double(x+(1.333*leaves_radius),
y+(0.667*leaves_radius),
leaves_radius/5,
leaves_radius/5);
// add fruit to the tree
GeneralPath wholeTree = this.get();
wholeTree.append(fruit1,false);
wholeTree.append(fruit2,false);
wholeTree.append(fruit3,false);
}
}
|
src/edu/ucsb/cs56/drawings/sswong/advanced/TreeWithFruits.java
|
package edu.ucsb.cs56.drawings.sswong.advanced;
import java.awt.geom.GeneralPath;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
/**
A Tree with Fruits
@author Simon Wong
@version for CS56, F16, UCSB
*/
public class TreeWithFruits extends Tree implements Shape{
public TreeWithFruits(double x, double y,
double leaves_radius,
double trunk_width,
double trunk_height)
{
// create the tree
super(x,y,leaves_radius,trunk_width,trunk_height);
// add three round fruits on the leaves, placed in a triangular fashion
Ellipse2D.Double fruit1 =
new Ellipse2D.Double(x+(0.667*leaves_radius),
y+(0.667*leaves_radius),
leaves_radius/5,
leaves_radius/5);
Ellipse2D.Double fruit2 =
new Ellipse2D.Double(x+leaves_radius,
y+(1.333*leaves_radius),
leaves_radius/5,
leaves_radius/5);
Ellipse2D.Double fruit3 =
new Ellipse2D.Double(x+(1.333*leaves_radius),
y+(0.667*leaves_radius),
leaves_radius/5,
leaves_radius/5);
// add fruit to the tree
GeneralPath wholeTree = this.get();
wholeTree.append(fruit1,false);
wholeTree.append(fruit2,false);
wholeTree.append(fruit3,false);
}
}
|
Update TreeWithFruits.java
|
src/edu/ucsb/cs56/drawings/sswong/advanced/TreeWithFruits.java
|
Update TreeWithFruits.java
|
<ide><path>rc/edu/ucsb/cs56/drawings/sswong/advanced/TreeWithFruits.java
<ide>
<ide> public class TreeWithFruits extends Tree implements Shape{
<ide>
<add> /**
<add> Constructor
<add>
<add> @param x x coord of top left corner of tree
<add> @param y y coord of top left corner of tree
<add> @param leaves_radius radius of tree leaves
<add> @param trunk_width width of trunk
<add> @param trunk_height height of trunk
<add> */
<ide> public TreeWithFruits(double x, double y,
<ide> double leaves_radius,
<ide> double trunk_width,
|
|
Java
|
apache-2.0
|
e69fc10ae17fcb2dfdd5e406ac61e9ee2c34c277
| 0 |
dannil/HttpDownloader,dannil/HttpDownloader
|
package org.dannil.httpdownloader.utility;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
public final class LanguageUtility {
private final static Logger LOGGER = Logger.getLogger(LanguageUtility.class.getName());
private static final Locale DEFAULT_LOCALE;
private static final List<Locale> availableLanguages;
private LanguageUtility() {
throw new UnsupportedOperationException();
}
static {
DEFAULT_LOCALE = new Locale("en", "US");
availableLanguages = new LinkedList<Locale>();
availableLanguages.add(new Locale("en", "US"));
availableLanguages.add(new Locale("sv", "SE"));
}
/**
* Return a language bundle which matches the user's current display language.
*
* @return a ResourceBundle with a collection of localized language strings, in the default language
*/
private static final ResourceBundle getLanguage() {
return getLanguage(Locale.getDefault());
}
/**
* Return a language bundle which matches the inputed locale.
*
* @param locale
* the language file to load
*
* @return a ResourceBundle with a collection of localized language strings, in the inputed locale
*/
private static final ResourceBundle getLanguage(final Locale locale) {
if (availableLanguages.contains(locale)) {
return ResourceBundle.getBundle(PathUtility.PATH_LANGUAGE, locale);
}
return ResourceBundle.getBundle(PathUtility.PATH_LANGUAGE, DEFAULT_LOCALE);
}
/**
* Return a language bundle which matches the language currently in the session. If there isn't
* a language in the session, return the default display language.
*
* @param session
* the session to check for the language
*
* @return a language bundle which matches either the language in the session or the default display language
*
* @see org.dannil.httpdownloader.utility.LanguageUtility#getLanguage(Locale)
*/
public static final ResourceBundle getLanguage(final HttpSession session) {
if (!session.getAttribute("language").equals(getLanguage())) {
// The user has specifically entered another language in the session
// which differs from the default display language. We proceed to
// load the specified language instead of the default
return getLanguage((Locale) session.getAttribute("language"));
}
// The user hasn't specified another language; load the default
// display language
return getLanguage();
}
}
|
src/main/java/org/dannil/httpdownloader/utility/LanguageUtility.java
|
package org.dannil.httpdownloader.utility;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
public final class LanguageUtility {
private final static Logger LOGGER = Logger.getLogger(LanguageUtility.class.getName());
private static final Locale DEFAULT_LOCALE;
private static final List<Locale> availableLanguages;
private LanguageUtility() {
throw new UnsupportedOperationException();
}
static {
DEFAULT_LOCALE = new Locale("en", "US");
availableLanguages = new LinkedList<Locale>();
availableLanguages.add(new Locale("en", "US"));
availableLanguages.add(new Locale("sv", "SE"));
}
/**
* Return a language bundle which matches the user's current display language.
*
* @return a ResourceBundle with a collection of localized language strings, in the default language
*/
public static final ResourceBundle getLanguage() {
return getLanguage(Locale.getDefault());
}
/**
* Return a language bundle which matches the inputed locale.
*
* @param locale
* the language file to load
*
* @return a ResourceBundle with a collection of localized language strings, in the inputed locale
*
* @see org.dannil.httpdownloader.utility.ResourceUtility#getResourceBundle(String, Locale)
*/
public static final ResourceBundle getLanguage(final Locale locale) {
return getLanguageBundle(PathUtility.PATH_LANGUAGE, locale);
}
/**
* Return a language bundle which matches the language currently in the session. If there isn't
* a language in the session, return the default display language.
*
* @param session
* the session to check for the language
*
* @return a language bundle which matches either the language in the session or the default display language
*/
public static final ResourceBundle getLanguage(final HttpSession session) {
if (!session.getAttribute("language").equals(getLanguage())) {
// The user has specifically entered another language in the session
// which differs from the default display language. We proceed to
// load the specified language instead of the default
return getLanguage((Locale) session.getAttribute("language"));
}
// The user hasn't specified another language; load the default
// display language
return getLanguage();
}
/**
* Return a resource bundle from the specified path with matches the specified locale.
* If the file for the inputed locale doesn't exist, return a standard language (enUS).
*
* @param path
* the path of the file to load
* @param locale
* the locale of the file to load
*
* @return a ResourceBundle containing the file which matches the specified path and locale
*/
private static final ResourceBundle getLanguageBundle(final String path, final Locale locale) {
if (availableLanguages.contains(locale)) {
return ResourceBundle.getBundle(path, locale);
}
return getLanguageBundle(path, DEFAULT_LOCALE);
}
}
|
Optimized code
|
src/main/java/org/dannil/httpdownloader/utility/LanguageUtility.java
|
Optimized code
|
<ide><path>rc/main/java/org/dannil/httpdownloader/utility/LanguageUtility.java
<ide> *
<ide> * @return a ResourceBundle with a collection of localized language strings, in the default language
<ide> */
<del> public static final ResourceBundle getLanguage() {
<add> private static final ResourceBundle getLanguage() {
<ide> return getLanguage(Locale.getDefault());
<ide> }
<ide>
<ide> * the language file to load
<ide> *
<ide> * @return a ResourceBundle with a collection of localized language strings, in the inputed locale
<del> *
<del> * @see org.dannil.httpdownloader.utility.ResourceUtility#getResourceBundle(String, Locale)
<ide> */
<del> public static final ResourceBundle getLanguage(final Locale locale) {
<del> return getLanguageBundle(PathUtility.PATH_LANGUAGE, locale);
<add> private static final ResourceBundle getLanguage(final Locale locale) {
<add> if (availableLanguages.contains(locale)) {
<add> return ResourceBundle.getBundle(PathUtility.PATH_LANGUAGE, locale);
<add> }
<add> return ResourceBundle.getBundle(PathUtility.PATH_LANGUAGE, DEFAULT_LOCALE);
<ide> }
<ide>
<ide> /**
<ide> * the session to check for the language
<ide> *
<ide> * @return a language bundle which matches either the language in the session or the default display language
<add> *
<add> * @see org.dannil.httpdownloader.utility.LanguageUtility#getLanguage(Locale)
<ide> */
<ide> public static final ResourceBundle getLanguage(final HttpSession session) {
<ide> if (!session.getAttribute("language").equals(getLanguage())) {
<ide> // display language
<ide> return getLanguage();
<ide> }
<del>
<del> /**
<del> * Return a resource bundle from the specified path with matches the specified locale.
<del> * If the file for the inputed locale doesn't exist, return a standard language (enUS).
<del> *
<del> * @param path
<del> * the path of the file to load
<del> * @param locale
<del> * the locale of the file to load
<del> *
<del> * @return a ResourceBundle containing the file which matches the specified path and locale
<del> */
<del> private static final ResourceBundle getLanguageBundle(final String path, final Locale locale) {
<del> if (availableLanguages.contains(locale)) {
<del> return ResourceBundle.getBundle(path, locale);
<del> }
<del> return getLanguageBundle(path, DEFAULT_LOCALE);
<del> }
<del>
<ide> }
|
|
Java
|
apache-2.0
|
347b7a9b6d7ccca768aeb35cdf411e838b1903cb
| 0 |
dmmiller612/javers,javers/javers,javers/javers
|
package org.javers.core.examples;
import org.javers.core.Javers;
import org.javers.core.JaversBuilder;
import org.javers.core.diff.Diff;
import org.javers.core.diff.changetype.NewObject;
import org.javers.core.diff.changetype.ObjectRemoved;
import org.javers.core.diff.changetype.ReferenceChange;
import org.javers.core.diff.changetype.ValueChange;
import org.javers.core.examples.model.Employee;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
/**
* @author bartosz walacik
*/
public class EmployeeHierarchiesDiffExample {
@Test
public void shouldDetectSalaryChange(){
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Noisy Manager"),
new Employee("Great Developer", 10000));
Employee newBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Noisy Manager"),
new Employee("Great Developer", 20000));
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
ValueChange change = diff.getChangesByType(ValueChange.class).get(0);
assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
assertThat(change.getProperty().getName()).isEqualTo("salary");
assertThat(change.getLeft()).isEqualTo(10000);
assertThat(change.getRight()).isEqualTo(20000);
System.out.println("diff: " + javers.toJson(diff));
}
@Test
public void shouldDetectHired() {
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Great Developer"));
Employee newBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Great Developer"),
new Employee("Hired One"),
new Employee("Hired Second"));
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
assertThat(diff.getObjectsByChangeType(NewObject.class))
.hasSize(2)
.containsOnly(new Employee("Hired One"),
new Employee("Hired Second"));
System.out.println("diff: " + javers.toJson(diff));
}
@Test
public void shouldDetectBossChange() {
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Manager One")
.addSubordinate(new Employee("Great Developer")),
new Employee("Manager Second"));
Employee newBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Manager One"),
new Employee("Manager Second")
.addSubordinate(new Employee("Great Developer")));
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
ReferenceChange change = diff.getChangesByType(ReferenceChange.class).get(0);
assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
assertThat(change.getLeft().getCdoId()).isEqualTo("Manager One");
assertThat(change.getRight().getCdoId()).isEqualTo("Manager Second");
System.out.println("diff: " + javers.toJson(diff));
}
@Test
public void shouldDetectFiredForLargeDepthStructure() {
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss");
Employee boss = oldBoss;
for (int i=0; i<1000; i++){
boss.addSubordinate(new Employee("Emp no."+i));
boss = boss.getSubordinates().get(0);
}
Employee newBoss = new Employee("Big Boss");
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
assertThat(diff.getChangesByType(ObjectRemoved.class)).hasSize(1000);
}
}
|
javers-core/src/test/java/org/javers/core/examples/EmployeeHierarchiesDiffExample.java
|
package org.javers.core.examples;
import org.javers.core.Javers;
import org.javers.core.JaversBuilder;
import org.javers.core.diff.Diff;
import org.javers.core.diff.changetype.NewObject;
import org.javers.core.diff.changetype.ObjectRemoved;
import org.javers.core.diff.changetype.ReferenceChange;
import org.javers.core.diff.changetype.ValueChange;
import org.javers.core.examples.model.Employee;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
/**
* @author bartosz walacik
*/
public class EmployeeHierarchiesDiffExample {
@Test
public void shouldDetectSalaryChange(){
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Noisy Manager"),
new Employee("Great Developer", 10000));
Employee newBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Noisy Manager"),
new Employee("Great Developer", 20000));
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
ValueChange change = diff.getChangesByType(ValueChange.class).get(0);
assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
assertThat(change.getProperty().getName()).isEqualTo("salary");
assertThat(change.getLeft()).isEqualTo(10000);
assertThat(change.getRight()).isEqualTo(20000);
System.out.println("diff: " + javers.toJson(diff));
}
@Test
public void shouldDetectHired() {
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Great Developer"));
Employee newBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Great Developer"),
new Employee("Hired One"),
new Employee("Hired Second"));
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
assertThat(diff.getObjectsByChangeType(NewObject.class))
.hasSize(2)
.containsOnly(new Employee("Hired One"),
new Employee("Hired Second"));
System.out.println("diff: " + javers.toJson(diff));
}
@Test
public void shouldDetectBossChange() {
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Manager One")
.addSubordinate(new Employee("Great Developer")),
new Employee("Manager Second"));
Employee newBoss = new Employee("Big Boss")
.addSubordinates(
new Employee("Manager One"),
new Employee("Manager Second")
.addSubordinate(new Employee("Great Developer")));
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
ReferenceChange change = diff.getChangesByType(ReferenceChange.class).get(0);
assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
assertThat(change.getLeft().getCdoId()).isEqualTo("Manager One");
assertThat(change.getRight().getCdoId()).isEqualTo("Manager Second");
System.out.println("diff: " + javers.toJson(diff));
}
@Test
public void shouldDetectFiredForLargeDepthStructure() {
//given
Javers javers = JaversBuilder.javers().build();
Employee oldBoss = new Employee("Big Boss");
Employee boss = oldBoss;
for (int i=0; i<1000; i++){
Employee emp = new Employee("Emp no."+i);
boss.addSubordinate(emp);
boss = emp;
}
Employee newBoss = new Employee("Big Boss");
//when
Diff diff = javers.compare(oldBoss, newBoss);
//then
assertThat(diff.getChangesByType(ObjectRemoved.class)).hasSize(1000);
}
}
|
shouldDetectFiredForLargeDepthStructure, fix
|
javers-core/src/test/java/org/javers/core/examples/EmployeeHierarchiesDiffExample.java
|
shouldDetectFiredForLargeDepthStructure, fix
|
<ide><path>avers-core/src/test/java/org/javers/core/examples/EmployeeHierarchiesDiffExample.java
<ide> Employee oldBoss = new Employee("Big Boss");
<ide> Employee boss = oldBoss;
<ide> for (int i=0; i<1000; i++){
<del> Employee emp = new Employee("Emp no."+i);
<del> boss.addSubordinate(emp);
<del> boss = emp;
<add> boss.addSubordinate(new Employee("Emp no."+i));
<add> boss = boss.getSubordinates().get(0);
<ide> }
<ide>
<ide> Employee newBoss = new Employee("Big Boss");
|
|
Java
|
mit
|
88ee274d3c3489c7988a50d1ae69bd8734525835
| 0 |
nunull/QuickStarter,nunull/QuickStarter,nunull/QuickStarter,nunull/QuickStarter
|
package de.dqi11.quickStarter.os;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
/**
* Wrapper for Mac OSX.
*/
public class MacOS extends OS implements NativeKeyListener {
private boolean ctrlKeyPressed = false;
public MacOS() {
try {
GlobalScreen.registerNativeHook();
GlobalScreen.getInstance().addNativeKeyListener(this);
} catch (NativeHookException e) {
e.printStackTrace();
}
}
@Override
public void shutdown() {
GlobalScreen.unregisterNativeHook();
}
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
if(isActive()) {
if(e.getKeyCode() == 16 && e.getModifiers() == 2) ctrlKeyPressed = true;
else if(e.getKeyCode() == 32 && ctrlKeyPressed) toggleApp();
}
}
@Override
public void nativeKeyReleased(NativeKeyEvent e) {
if(e.getKeyCode() == 16) ctrlKeyPressed = false;
}
@Override
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
|
src/de/dqi11/quickStarter/os/MacOS.java
|
package de.dqi11.quickStarter.os;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
/**
* Wrapper for Mac OSX.
*/
public class MacOS extends OS implements NativeKeyListener {
private boolean altKeyPressed = false;
public MacOS() {
try {
GlobalScreen.registerNativeHook();
GlobalScreen.getInstance().addNativeKeyListener(this);
} catch (NativeHookException e) {
e.printStackTrace();
}
}
@Override
public void shutdown() {
GlobalScreen.unregisterNativeHook();
}
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
if (isActive()){
if(e.getKeyCode() == 16) altKeyPressed = true;
else if(e.getKeyCode() == 32 && altKeyPressed) toggleApp();
}
}
@Override
public void nativeKeyReleased(NativeKeyEvent e) {
if(e.getKeyCode() == 16) altKeyPressed = false;
}
@Override
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
|
Fixes bug of MacOS global keyboard shortcut
|
src/de/dqi11/quickStarter/os/MacOS.java
|
Fixes bug of MacOS global keyboard shortcut
|
<ide><path>rc/de/dqi11/quickStarter/os/MacOS.java
<ide> */
<ide> public class MacOS extends OS implements NativeKeyListener {
<ide>
<del> private boolean altKeyPressed = false;
<add> private boolean ctrlKeyPressed = false;
<ide>
<ide> public MacOS() {
<ide> try {
<ide>
<ide> @Override
<ide> public void nativeKeyPressed(NativeKeyEvent e) {
<del> if (isActive()){
<del> if(e.getKeyCode() == 16) altKeyPressed = true;
<del> else if(e.getKeyCode() == 32 && altKeyPressed) toggleApp();
<add> if(isActive()) {
<add> if(e.getKeyCode() == 16 && e.getModifiers() == 2) ctrlKeyPressed = true;
<add> else if(e.getKeyCode() == 32 && ctrlKeyPressed) toggleApp();
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void nativeKeyReleased(NativeKeyEvent e) {
<del> if(e.getKeyCode() == 16) altKeyPressed = false;
<add> if(e.getKeyCode() == 16) ctrlKeyPressed = false;
<ide> }
<ide>
<ide> @Override
|
|
JavaScript
|
mit
|
3309c3a3842105902eb6539f9cf026ff00d5ad18
| 0 |
quidmonkey/elisse,quidmonkey/elisse,quidmonkey/elisse
|
'use strict';
var config = require('../config');
var gulp = require('gulp');
var rename = require('gulp-rename');
var stylint = require('gulp-stylint');
var stylus = require('gulp-stylus');
module.exports = gulp.task('styles-build', function () {
return gulp.src(config.styl)
.pipe(stylint({ config: '.stylintrc' }))
.pipe(stylus({ compress: true }))
.pipe(rename(config.build.css))
.pipe(gulp.dest(config.dist));
});
|
gulp/tasks/styles-build.js
|
'use strict';
var config = require('../config');
var gulp = require('gulp');
var rename = require('gulp-rename');
var stylint = require('gulp-stylint');
var stylus = require('gulp-stylus');
module.exports = gulp.task('stylus-build', function () {
return gulp.src(config.styl)
.pipe(stylint({ config: '.stylintrc' }))
.pipe(stylus({ compress: true }))
.pipe(rename(config.build.css))
.pipe(gulp.dest(config.dist));
});
|
Renamed gulp task stylus-build to styles-build.
|
gulp/tasks/styles-build.js
|
Renamed gulp task stylus-build to styles-build.
|
<ide><path>ulp/tasks/styles-build.js
<ide> var stylint = require('gulp-stylint');
<ide> var stylus = require('gulp-stylus');
<ide>
<del>module.exports = gulp.task('stylus-build', function () {
<add>module.exports = gulp.task('styles-build', function () {
<ide> return gulp.src(config.styl)
<ide> .pipe(stylint({ config: '.stylintrc' }))
<ide> .pipe(stylus({ compress: true }))
|
|
Java
|
apache-2.0
|
e667562a28597749ac97350329767cd7f6fb6322
| 0 |
bryanchou/cat,wyzssw/cat,chinaboard/cat,bryanchou/cat,dadarom/cat,michael8335/cat,chinaboard/cat,chqlb/cat,unidal/cat,redbeans2015/cat,bryanchou/cat,dianping/cat,gspandy/cat,JacksonSha/cat,chinaboard/cat,dianping/cat,unidal/cat,unidal/cat,michael8335/cat,javachengwc/cat,cdljsj/cat,itnihao/cat,michael8335/cat,javachengwc/cat,chqlb/cat,javachengwc/cat,itnihao/cat,ddviplinux/cat,howepeng/cat,cdljsj/cat,wuqiangxjtu/cat,howepeng/cat,xiaojiaqi/cat,javachengwc/cat,gspandy/cat,gspandy/cat,wuqiangxjtu/cat,cdljsj/cat,howepeng/cat,unidal/cat,dianping/cat,TonyChai24/cat,JacksonSha/cat,javachengwc/cat,JacksonSha/cat,cdljsj/cat,TonyChai24/cat,unidal/cat,dadarom/cat,jialinsun/cat,dianping/cat,michael8335/cat,jialinsun/cat,chqlb/cat,redbeans2015/cat,ddviplinux/cat,redbeans2015/cat,itnihao/cat,itnihao/cat,gspandy/cat,dadarom/cat,dadarom/cat,chinaboard/cat,ddviplinux/cat,howepeng/cat,TonyChai24/cat,redbeans2015/cat,xiaojiaqi/cat,bryanchou/cat,jialinsun/cat,chinaboard/cat,howepeng/cat,xiaojiaqi/cat,itnihao/cat,dianping/cat,wyzssw/cat,chinaboard/cat,wyzssw/cat,javachengwc/cat,ddviplinux/cat,bryanchou/cat,jialinsun/cat,wuqiangxjtu/cat,jialinsun/cat,wyzssw/cat,JacksonSha/cat,chqlb/cat,JacksonSha/cat,michael8335/cat,TonyChai24/cat,dianping/cat,cdljsj/cat,gspandy/cat,wuqiangxjtu/cat,dadarom/cat,gspandy/cat,redbeans2015/cat,redbeans2015/cat,xiaojiaqi/cat,michael8335/cat,wyzssw/cat,wuqiangxjtu/cat,howepeng/cat,TonyChai24/cat,dianping/cat,ddviplinux/cat,wuqiangxjtu/cat,chqlb/cat,TonyChai24/cat,bryanchou/cat,chqlb/cat,jialinsun/cat,dadarom/cat,xiaojiaqi/cat,unidal/cat,JacksonSha/cat,cdljsj/cat,ddviplinux/cat,itnihao/cat,xiaojiaqi/cat,wyzssw/cat
|
package com.dianping.cat.helper;
import java.util.Calendar;
import java.util.Date;
public class TimeHelper {
public static final long ONE_MINUTE = 60 * 1000L;
public static final long ONE_HOUR = 60 * 60 * 1000L;
public static final long ONE_DAY = 24 * ONE_HOUR;
public static final long ONE_WEEK = 7 * ONE_DAY;
public static Date addDays(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}
public static Date getCurrentDay() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getCurrentDay(int index) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, index);
return cal.getTime();
}
public static Date getCurrentDay(long timestamp) {
return getCurrentDay(timestamp, 0);
}
public static Date getCurrentDay(long timestamp, int index) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, index);
return cal.getTime();
}
public static Date getCurrentHour() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getCurrentHour(int index) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.HOUR_OF_DAY, index);
return cal.getTime();
}
public static Date getCurrentMinute() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getCurrentMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
// get lastest sarterday
public static Date getCurrentWeek() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 7) {
return cal.getTime();
} else {
cal.add(Calendar.DATE, -dayOfWeek);
}
return cal.getTime();
}
public static Date getLastMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MONTH, -1);
return cal.getTime();
}
public static String getMinuteStr() {
int minute = Calendar.getInstance().get(Calendar.MINUTE);
String minuteStr = String.valueOf(minute);
if (minute < 10) {
minuteStr = '0' + minuteStr;
}
return "M" + minuteStr;
}
public static Date getYesterday() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
public static boolean sleepToNextMinute() {
try {
long current = System.currentTimeMillis();
Thread.sleep(ONE_MINUTE - current % ONE_MINUTE);
return true;
} catch (InterruptedException e) {
return false;
}
}
}
|
cat-home/src/main/java/com/dianping/cat/helper/TimeHelper.java
|
package com.dianping.cat.helper;
import java.util.Calendar;
import java.util.Date;
public class TimeHelper {
public static final long ONE_MINUTE = 60 * 1000L;
public static final long ONE_HOUR = 60 * 60 * 1000L;
public static final long ONE_DAY = 24 * ONE_HOUR;
public static final long ONE_WEEK = 7 * ONE_DAY;
public static Date addDays(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}
public static Date getCurrentDay() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getCurrentDay(int index) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, index);
return cal.getTime();
}
public static Date getCurrentDay(long timestamp) {
return getCurrentDay(timestamp, 0);
}
public static Date getCurrentDay(long timestamp, int index) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, index);
return cal.getTime();
}
public static Date getCurrentHour() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getCurrentHour(int index) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.HOUR_OF_DAY, index);
return cal.getTime();
}
public static Date getCurrentMinute() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getCurrentMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
// get lastest sarterday
public static Date getCurrentWeek() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 7) {
return cal.getTime();
} else {
cal.add(Calendar.DATE, -dayOfWeek);
}
return cal.getTime();
}
public static Date getLastMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MONTH, -1);
return cal.getTime();
}
public static String getMinuteStr() {
int minute = Calendar.getInstance().get(Calendar.MINUTE);
String minuteStr = String.valueOf(minute);
if (minute < 10) {
minuteStr = '0' + minuteStr;
}
return "M" + minuteStr;
}
public static Date getYesterday() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
public static boolean sleepToNextMinute() {
try {
Calendar cal = Calendar.getInstance();
int seconds = cal.get(Calendar.SECOND);
Thread.sleep(60 - seconds);
return true;
} catch (InterruptedException e) {
return false;
}
}
}
|
refactor the time helper
|
cat-home/src/main/java/com/dianping/cat/helper/TimeHelper.java
|
refactor the time helper
|
<ide><path>at-home/src/main/java/com/dianping/cat/helper/TimeHelper.java
<ide>
<ide> public static boolean sleepToNextMinute() {
<ide> try {
<del> Calendar cal = Calendar.getInstance();
<del> int seconds = cal.get(Calendar.SECOND);
<del>
<del> Thread.sleep(60 - seconds);
<add> long current = System.currentTimeMillis();
<add>
<add> Thread.sleep(ONE_MINUTE - current % ONE_MINUTE);
<ide> return true;
<ide> } catch (InterruptedException e) {
<ide> return false;
|
|
Java
|
mpl-2.0
|
3a93f0abeb22acad9873d0561e07855e5f125fcb
| 0 |
hivex-unipd/swedesigner,hivex-unipd/swedesigner,hivex-unipd/swedesigner
|
package server.check;
import java.util.ArrayList;
import java.util.List;
import server.project.ParsedAttribute;
import server.project.ParsedClass;
import server.project.ParsedInstruction;
import server.project.ParsedInterface;
import server.project.ParsedMethod;
/* è stato aggiunto un campo dati Check checker all'interno della classe JavaGenerator (istanziato sempre utilizzando
* un @Bean di Spring). Sarà tale classe che, prima di generare il codice, provvederà sui tipi ciclati ad invocare la corrispondente
* funzione void check(Check checker) e verificare così se sono conformi o no alle principali regole del linguaggio target (vedi JavaGenerator.java).
* */
public class JavaCheck implements Check {
/*PRE: devo comunque considerare che il Parser costruisce dei ParsedElement con all'interno già
* i campi obbligatori per i diagrammi scelti (es. per un attributo ci saranno SEMPRE il nome e il tipo)
* (forse che comunque è necessario un ulteriore controllo?)
*/
@Override
public void checkClass(ParsedClass pc) throws LanguageException{
}
@Override
public void checkInterface(ParsedInterface pi) throws LanguageException{
}
@Override
public void checkAttribute(ParsedAttribute pa) throws LanguageException{
}
@Override
//si tratta solo di un esempio di funzionamento di questo metodo, poco è effettivamente implementato
public void checkMethod(ParsedMethod pm) throws LanguageException{
//il parser mi assicura che ogni metodo ha sempre almeno il NOME e il TIPO DI RITORNO;
//per prima cosa controllo la lista degli argomenti
//preparo una lista dove memorizzare tutti gli errori che saranno poi inseriti eventualmente nell'eccezione che sarà lanciata
List<String> errors = new ArrayList<String>();
//per prima cosa controllo che gli argomenti siano tutti legali
List<ParsedAttribute> args = pm.getArgs();
for(int i=0; i<args.size(); i++){
/*try{ //args.get(i).check(this); si tratta di un metodo non ancora implementato (vedi commento ParsedElement);
}catch(LanguageException e){
//faccio il merge delle due liste
errors.addAll(e.getErrors());
}*/
}
List<ParsedInstruction> body = pm.getBody();
//controllo l'effettiva astrattezza
if(pm.getIs_abstract())
if(pm.getBody()!=null)
errors.add("Java language error: method "+pm.getName()+" is declared abstract but has implemented body");
else//controllo che tutte le istruzioni del metodo siano legali nel linguaggio Java
for(int i=0; i<body.size(); i++){
/*try{
//body.get(i).check(this); si tratta di un metodo non ancora implementato (vedi commento ParsedElement);
}catch(LanguageException e){
//faccio il merge delle due liste
errors.addAll(e.getErrors());
}*/
}
if(errors.size()!=0)
throw new LanguageException(errors);
}
}
|
src/main/java/server/check/JavaCheck.java
|
package server.check;
import java.util.ArrayList;
import java.util.List;
import server.project.ParsedAttribute;
import server.project.ParsedClass;
import server.project.ParsedInstruction;
import server.project.ParsedInterface;
import server.project.ParsedMethod;
/* è stato aggiunto un campo dati Check checker all'interno della classe JavaGenerator (istanziato sempre utilizzando
* un @Bean di Spring). Sarà tale classe che, prima di generare il codice, provvederà sui tipi ciclati ad invocare la corrispondente
* funzione void check(Check checker) e verificare così se sono conformi o no alle principali regole del linguaggio target (vedi JavaGenerator.java).
* */
public class JavaCheck implements Check {
/*PRE: devo comunque considerare che il Parser costruisce dei ParsedElement con all'interno già
* i campi obbligatori per i diagrammi scelti (es. per un attributo ci saranno SEMPRE il nome e il tipo)
* (forse che comunque è necessario un ulteriore controllo?)
*/
@Override
public void checkClass(ParsedClass pc) throws LanguageException{
}
@Override
public void checkInterface(ParsedInterface pi) throws LanguageException{
}
@Override
public void checkAttribute(ParsedAttribute pa) throws LanguageException{
}
@Override
//si tratta solo di un esempio di funzionamento di questo metodo, poco è effettivamente implementato
public void checkMethod(ParsedMethod pm) throws LanguageException{
//il parser mi assicura che ogni metodo ha sempre almeno il NOME e il TIPO DI RITORNO;
//per prima cosa controllo la lista degli argomenti
//preparo una lista dove memorizzare tutti gli errori che saranno poi inseriti eventualmente nell'eccezione che sarà lanciata
List<String> errors = new ArrayList<String>();
//per prima cosa controllo che gli argomenti siano tutti legali
List<ParsedAttribute> args = pm.getArgs();
for(int i=0; i<args.size(); i++){
try{ //args.get(i).check(this); si tratta di un metodo non ancora implementato (vedi commento ParsedElement);
}catch(LanguageException e){
//faccio il merge delle due liste
errors.addAll(e.getErrors());
}
}
List<ParsedInstruction> body = pm.getBody();
//controllo l'effettiva astrattezza
if(pm.getIs_abstract())
if(pm.getBody()!=null)
errors.add("Java language error: method "+pm.getName()+" is declared abstract but has implemented body");
else//controllo che tutte le istruzioni del metodo siano legali nel linguaggio Java
for(int i=0; i<body.size(); i++){
try{
//body.get(i).check(this); si tratta di un metodo non ancora implementato (vedi commento ParsedElement);
}catch(LanguageException e){
//faccio il merge delle due liste
errors.addAll(e.getErrors());
}
}
if(errors.size()!=0)
throw new LanguageException(errors);
}
}
|
commentato codice
|
src/main/java/server/check/JavaCheck.java
|
commentato codice
|
<ide><path>rc/main/java/server/check/JavaCheck.java
<ide> //per prima cosa controllo che gli argomenti siano tutti legali
<ide> List<ParsedAttribute> args = pm.getArgs();
<ide> for(int i=0; i<args.size(); i++){
<del> try{ //args.get(i).check(this); si tratta di un metodo non ancora implementato (vedi commento ParsedElement);
<add> /*try{ //args.get(i).check(this); si tratta di un metodo non ancora implementato (vedi commento ParsedElement);
<ide> }catch(LanguageException e){
<ide> //faccio il merge delle due liste
<ide> errors.addAll(e.getErrors());
<del> }
<add> }*/
<ide> }
<ide>
<ide> List<ParsedInstruction> body = pm.getBody();
<ide> errors.add("Java language error: method "+pm.getName()+" is declared abstract but has implemented body");
<ide> else//controllo che tutte le istruzioni del metodo siano legali nel linguaggio Java
<ide> for(int i=0; i<body.size(); i++){
<del> try{
<add> /*try{
<ide> //body.get(i).check(this); si tratta di un metodo non ancora implementato (vedi commento ParsedElement);
<ide> }catch(LanguageException e){
<ide> //faccio il merge delle due liste
<ide> errors.addAll(e.getErrors());
<del> }
<add> }*/
<ide> }
<ide> if(errors.size()!=0)
<ide> throw new LanguageException(errors);
|
|
JavaScript
|
mit
|
f6f1ce5ce27748b7f5fa0840ca31789824bdaa42
| 0 |
nodeca/nodeca.core,nodeca/nodeca.core
|
// Client utils for test environment (PhantomJS)
'use strict';
/*global window, NodecaLoader, $*/
/*eslint no-console: 0*/
// Expose assert
window.assert = window.chai.assert;
// Expose N
window.TEST = { N: NodecaLoader.N };
var oldAssertionErrorToString = window.chai.AssertionError.prototype.toString;
window.chai.AssertionError.prototype.toString = function () {
// Error handler in PhantomJS automatically call `toString`. To get whole error
// data send serialized error through console handler.
console.log('AssertionError:' + JSON.stringify(this.toJSON()));
// Call default `toString` method
return oldAssertionErrorToString.call(this);
};
// Do click by element and wait for finish
//
// - selector (String) - css selector of element
// - wireChannel (String) - optional, channel to listen for operation finish (from `data-on-click` by default)
// - event (String) - optional, HTML event name (click by default)
// - callback - function to execute on complete
//
//
// .evaluateAsync(function (done) {
// trigger('[data-on-click="users.albums_root.create_album"]', function () {
// $('input[name="album_name"]').val('new test album!');
//
// trigger('.modal-dialog button[type="submit"]', 'io.complete:users.albums_root.list', function () {
// assert.equal($('.user-albumlist li:last .thumb-caption__line:first').text(), 'new test album!');
// done();
// });
// });
// })
//
window.trigger = function (selector, wireChannel, event, callback) {
// Normalize arguments
if (arguments.length === 2) {
callback = wireChannel;
wireChannel = undefined;
} else if (arguments.length === 3) {
callback = event;
event = undefined;
}
var $element = $(selector);
var channel = wireChannel ? wireChannel : $element.data('onClick');
NodecaLoader.N.wire.once(channel, { priority: 999 }, callback);
$element.trigger(event ? event : 'click');
};
|
lib/test/setup_client_env.js
|
// Client utils for test environment (PhantomJS)
'use strict';
/*global window, NodecaLoader, $*/
/*eslint no-console: 0*/
// Expose assert
window.assert = window.chai.assert;
var oldAssertionErrorToString = window.chai.AssertionError.prototype.toString;
window.chai.AssertionError.prototype.toString = function () {
// Error handler in PhantomJS automatically call `toString`. To get whole error
// data send serialized error through console handler.
console.log('AssertionError:' + JSON.stringify(this.toJSON()));
// Call default `toString` method
return oldAssertionErrorToString.call(this);
};
// Do click by element and wait for finish
//
// - selector (String) - css selector of element
// - wireChannel (String) - optional, channel to listen for operation finish (from `data-on-click` by default)
// - event (String) - optional, HTML event name (click by default)
// - callback - function to execute on complete
//
//
// .evaluateAsync(function (done) {
// trigger('[data-on-click="users.albums_root.create_album"]', function () {
// $('input[name="album_name"]').val('new test album!');
//
// trigger('.modal-dialog button[type="submit"]', 'io.complete:users.albums_root.list', function () {
// assert.equal($('.user-albumlist li:last .thumb-caption__line:first').text(), 'new test album!');
// done();
// });
// });
// })
//
window.trigger = function (selector, wireChannel, event, callback) {
// Normalize arguments
if (arguments.length === 2) {
callback = wireChannel;
wireChannel = undefined;
} else if (arguments.length === 3) {
callback = event;
event = undefined;
}
var $element = $(selector);
var channel = wireChannel ? wireChannel : $element.data('onClick');
NodecaLoader.N.wire.once(channel, { priority: 999 }, callback);
$element.trigger(event ? event : 'click');
};
|
Added alias "TEST.N" to clinet testing API
|
lib/test/setup_client_env.js
|
Added alias "TEST.N" to clinet testing API
|
<ide><path>ib/test/setup_client_env.js
<ide>
<ide> // Expose assert
<ide> window.assert = window.chai.assert;
<add>
<add>
<add>// Expose N
<add>window.TEST = { N: NodecaLoader.N };
<ide>
<ide>
<ide> var oldAssertionErrorToString = window.chai.AssertionError.prototype.toString;
|
|
Java
|
apache-2.0
|
28e5df6fd34b36a0f8110d9ae7c1b6caa58ce3eb
| 0 |
rhuss/fabric8,chirino/fabric8v2,zmhassan/fabric8,EricWittmann/fabric8,zmhassan/fabric8,christian-posta/fabric8,dhirajsb/fabric8,rajdavies/fabric8,KurtStam/fabric8,chirino/fabric8v2,sobkowiak/fabric8,dhirajsb/fabric8,chirino/fabric8v2,EricWittmann/fabric8,KurtStam/fabric8,KurtStam/fabric8,zmhassan/fabric8,rajdavies/fabric8,sobkowiak/fabric8,rhuss/fabric8,sobkowiak/fabric8,EricWittmann/fabric8,rhuss/fabric8,chirino/fabric8v2,sobkowiak/fabric8,christian-posta/fabric8,christian-posta/fabric8,rhuss/fabric8,rajdavies/fabric8,rajdavies/fabric8,dhirajsb/fabric8,christian-posta/fabric8,dhirajsb/fabric8,KurtStam/fabric8,EricWittmann/fabric8,zmhassan/fabric8
|
/**
* Copyright 2005-2015 Red Hat, Inc.
* <p/>
* Red Hat 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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 io.fabric8.kubernetes.assertions;
import io.fabric8.utils.IOHelpers;
import org.assertj.core.api.Fail;
import org.assertj.core.api.MapAssert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Collect the logs from a number of pods so that they can be asserted on
*/
public class PodLogsAssert extends MapAssert<String, String> {
private static final transient Logger LOG = LoggerFactory.getLogger(PodLogsAssert.class);
private final String containerName;
private final Map<String, String> logPrefixes;
public PodLogsAssert(Map<String, String> actual, String containerName) {
this(actual, containerName, new HashMap<String, String>());
}
public PodLogsAssert(Map<String, String> actual, String containerName, Map<String, String> logPrefixes) {
super(actual);
this.containerName = containerName;
this.logPrefixes = logPrefixes;
writeLogs();
}
public PodLogsAssert afterText(String startText) {
Map<String, String> newLogs = new HashMap<>();
Map<String, String> prefixes = new HashMap<>();
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = value.indexOf(startText);
if (idx >= 0) {
int splitIdx = idx + startText.length();
String remaining = value.substring(splitIdx);
String prefix = value.substring(0, splitIdx);
newLogs.put(podName, remaining);
prefixes.put(podName, prefix);
}
}
return new PodLogsAssert(newLogs, containerName, prefixes);
}
public void containsText(String... texts) {
for (String text : texts) {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = value.indexOf(text);
if (idx < 0) {
Fail.fail("Log of pod " + podName + " in file: " + file + " does not contains text `" + text
+ "` at " + logFileCoords(podName, value, idx));
}
}
}
}
public void doesNotContainText(String... texts) {
for (String text : texts) {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = value.indexOf(text);
if (idx >= 0) {
Fail.fail("Log of pod " + podName + " in file: " + file + " contains text `" + text
+ "` at " + logFileCoords(podName, value, idx));
} else {
LOG.debug("does not contain '" + text + "' in Log of pod " + podName + " in file: " + file);
}
}
}
}
public void doesNotContainTextCount(int count, String... texts) {
if (count == 1) {
doesNotContainText(texts);
}
for (String text : texts) {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = 0;
for (int i = 0; idx >= 0 && i < count; i++) {
int next = value.indexOf(text, idx);
if (next >= 0) {
idx = next + 1;
} else {
idx = next;
}
}
if (idx >= 0) {
String logText = fullLogText(podName, value.substring(0, idx - 1));
Fail.fail("Log of pod " + podName + " in file: " + file + " contains text `" + text
+ "` " + count + " times with the last at at " + textCoords(logText));
} else {
LOG.debug("does not contain '" + text + "' in Log of pod " + podName + " in file: " + file + " " + count + " times");
}
}
}
}
/**
* Returns the coordinates in the log file of the end of the bit of text
*/
protected String logFileCoords(String podName, String value, int idx) {
String prefix = "";
if (value != null && value.length() > 0 && idx > 0) {
prefix = value.substring(0, idx);
}
String logText = fullLogText(podName, prefix);
return textCoords(logText);
}
protected String fullLogText(String podName, String text) {
String logText = text;
String logPrefix = logPrefixes.get(podName);
if (logPrefix != null) {
logText = logPrefix + logText;
}
return logText;
}
/**
* Returns the line number and column of the end of text
*/
public static String textCoords(String text) {
int line = 1;
int idx = 0;
while (true) {
int next =text.indexOf('\n', idx);
if (next < 0) {
break;
}
idx = next + 1;
line += 1;
}
int column = 1 + text.length() - idx;
return "" + line + ":" + column;
}
protected File podLogFileName(String podName) {
// lets return the file we use to store the pod logs
String basedir = System.getProperty("basedir", ".");
File dir = new File(basedir, "target/fabric8/systest/logs");
String name = podName;
if (containerName != null) {
name += "." + containerName;
}
name += ".log";
File answer = new File(dir, name);
answer.getParentFile().mkdirs();
return answer;
}
private void writeLogs() {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
String logText = fullLogText(podName, value);
File file = podLogFileName(podName);
try {
IOHelpers.writeFully(file, logText);
} catch (IOException e) {
LOG.error("Failed to write log of pod " + podName + " container:" + containerName + " to file: "+ file + ". " + e, e);
}
}
}
}
|
components/kubernetes-assertions/src/main/java/io/fabric8/kubernetes/assertions/PodLogsAssert.java
|
/**
* Copyright 2005-2015 Red Hat, Inc.
* <p/>
* Red Hat 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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 io.fabric8.kubernetes.assertions;
import io.fabric8.utils.IOHelpers;
import org.assertj.core.api.Fail;
import org.assertj.core.api.MapAssert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Collect the logs from a number of pods so that they can be asserted on
*/
public class PodLogsAssert extends MapAssert<String, String> {
private static final transient Logger LOG = LoggerFactory.getLogger(PodLogsAssert.class);
private final String containerName;
private final Map<String, String> logPrefixes;
public PodLogsAssert(Map<String, String> actual, String containerName) {
this(actual, containerName, new HashMap<String, String>());
}
public PodLogsAssert(Map<String, String> actual, String containerName, Map<String, String> logPrefixes) {
super(actual);
this.containerName = containerName;
this.logPrefixes = logPrefixes;
writeLogs();
}
public PodLogsAssert afterText(String startText) {
Map<String, String> newLogs = new HashMap<>();
Map<String, String> prefixes = new HashMap<>();
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = value.indexOf(startText);
if (idx >= 0) {
int splitIdx = idx + startText.length();
String remaining = value.substring(splitIdx);
String prefix = value.substring(0, splitIdx);
newLogs.put(podName, remaining);
prefixes.put(podName, prefix);
}
}
return new PodLogsAssert(newLogs, containerName, prefixes);
}
public void containsText(String... texts) {
for (String text : texts) {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = value.indexOf(text);
if (idx < 0) {
Fail.fail("Log of pod " + podName + " in file: " + file + " does not contains text `" + text
+ "` at " + logFileCoords(podName, value.substring(0, idx)));
}
}
}
}
public void doesNotContainText(String... texts) {
for (String text : texts) {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = value.indexOf(text);
if (idx >= 0) {
Fail.fail("Log of pod " + podName + " in file: " + file + " contains text `" + text
+ "` at " + logFileCoords(podName, value.substring(0, idx)));
} else {
LOG.debug("does not contain '" + text + "' in Log of pod " + podName + " in file: " + file);
}
}
}
}
public void doesNotContainTextCount(int count, String... texts) {
if (count == 1) {
doesNotContainText(texts);
}
for (String text : texts) {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
int idx = 0;
for (int i = 0; idx >= 0 && i < count; i++) {
int next = value.indexOf(text, idx);
if (next >= 0) {
idx = next + 1;
} else {
idx = next;
}
}
if (idx >= 0) {
Fail.fail("Log of pod " + podName + " in file: " + file + " contains text `" + text
+ "` " + count + " times with the last at at " + logFileCoords(podName, value.substring(0, idx - 1)));
} else {
LOG.debug("does not contain '" + text + "' in Log of pod " + podName + " in file: " + file + " " + count + " times");
}
}
}
}
/**
* Returns the coordinates in the log file of the end of the bit of text
*/
public String logFileCoords(String podName, String text) {
String logText = text;
String logPrefix = logPrefixes.get(podName);
if (logPrefix != null) {
logText = logPrefix + logText;
}
return textCoords(logText);
}
/**
* Returns the line number and column of the end of text
*/
public static String textCoords(String text) {
int line = 1;
int idx = 0;
while (true) {
int next =text.indexOf('\n', idx);
if (next < 0) {
break;
}
idx = next + 1;
line += 1;
}
int column = 1 + text.length() - idx;
return "" + line + ":" + column;
}
protected File podLogFileName(String podName) {
// lets return the file we use to store the pod logs
String basedir = System.getProperty("basedir", ".");
File dir = new File(basedir, "target/fabric8/systest/logs");
String name = podName;
if (containerName != null) {
name += "." + containerName;
}
name += ".log";
File answer = new File(dir, name);
answer.getParentFile().mkdirs();
return answer;
}
private void writeLogs() {
Set<Map.Entry<String, String>> entries = actual.entrySet();
for (Map.Entry<String, String> entry : entries) {
String podName = entry.getKey();
String value = entry.getValue();
File file = podLogFileName(podName);
try {
IOHelpers.writeFully(file, value);
} catch (IOException e) {
LOG.error("Failed to write log of pod " + podName + " container:" + containerName + " to file: "+ file + ". " + e, e);
}
}
}
}
|
avoid noise if there's no log yet and lets log to disk the entire log output
|
components/kubernetes-assertions/src/main/java/io/fabric8/kubernetes/assertions/PodLogsAssert.java
|
avoid noise if there's no log yet and lets log to disk the entire log output
|
<ide><path>omponents/kubernetes-assertions/src/main/java/io/fabric8/kubernetes/assertions/PodLogsAssert.java
<ide> int idx = value.indexOf(text);
<ide> if (idx < 0) {
<ide> Fail.fail("Log of pod " + podName + " in file: " + file + " does not contains text `" + text
<del> + "` at " + logFileCoords(podName, value.substring(0, idx)));
<add> + "` at " + logFileCoords(podName, value, idx));
<ide> }
<ide> }
<ide> }
<ide> int idx = value.indexOf(text);
<ide> if (idx >= 0) {
<ide> Fail.fail("Log of pod " + podName + " in file: " + file + " contains text `" + text
<del> + "` at " + logFileCoords(podName, value.substring(0, idx)));
<add> + "` at " + logFileCoords(podName, value, idx));
<ide> } else {
<ide> LOG.debug("does not contain '" + text + "' in Log of pod " + podName + " in file: " + file);
<ide> }
<ide> }
<ide> }
<ide> if (idx >= 0) {
<add> String logText = fullLogText(podName, value.substring(0, idx - 1));
<ide> Fail.fail("Log of pod " + podName + " in file: " + file + " contains text `" + text
<del> + "` " + count + " times with the last at at " + logFileCoords(podName, value.substring(0, idx - 1)));
<add> + "` " + count + " times with the last at at " + textCoords(logText));
<ide> } else {
<ide> LOG.debug("does not contain '" + text + "' in Log of pod " + podName + " in file: " + file + " " + count + " times");
<ide> }
<ide> }
<ide> }
<ide> }
<add>
<ide>
<ide> /**
<ide> * Returns the coordinates in the log file of the end of the bit of text
<ide> */
<del> public String logFileCoords(String podName, String text) {
<add> protected String logFileCoords(String podName, String value, int idx) {
<add> String prefix = "";
<add> if (value != null && value.length() > 0 && idx > 0) {
<add> prefix = value.substring(0, idx);
<add> }
<add> String logText = fullLogText(podName, prefix);
<add> return textCoords(logText);
<add> }
<add>
<add> protected String fullLogText(String podName, String text) {
<ide> String logText = text;
<ide> String logPrefix = logPrefixes.get(podName);
<ide> if (logPrefix != null) {
<ide> logText = logPrefix + logText;
<ide> }
<del> return textCoords(logText);
<add> return logText;
<ide> }
<ide>
<ide>
<ide> for (Map.Entry<String, String> entry : entries) {
<ide> String podName = entry.getKey();
<ide> String value = entry.getValue();
<add> String logText = fullLogText(podName, value);
<ide> File file = podLogFileName(podName);
<ide> try {
<del> IOHelpers.writeFully(file, value);
<add> IOHelpers.writeFully(file, logText);
<ide> } catch (IOException e) {
<ide> LOG.error("Failed to write log of pod " + podName + " container:" + containerName + " to file: "+ file + ". " + e, e);
<ide> }
|
|
JavaScript
|
mit
|
99382d3481439a30630cc20043afd56f1fcd49ef
| 0 |
jhiesey/instant.io,feross/instant.io,feross/instant.io,jhiesey/instant.io,feross/instant.io,jhiesey/instant.io
|
var compress = require('compression')
var cors = require('cors')
var express = require('express')
var http = require('http')
var pug = require('pug')
var path = require('path')
var twilio = require('twilio')
var url = require('url')
var util = require('util')
var config = require('../config')
var PORT = Number(process.argv[2]) || 4000
var CORS_WHITELIST = [
// Official WebTorrent site
'http://webtorrent.io',
'https://webtorrent.io',
// Favor to friends :)
'http://rollcall.audio',
'https://rollcall.audio'
]
var secret
try {
secret = require('../secret')
} catch (err) {}
var app = express()
var server = http.createServer(app)
// Trust "X-Forwarded-For" and "X-Forwarded-Proto" nginx headers
app.enable('trust proxy')
// Disable "powered by express" header
app.set('x-powered-by', false)
// Use pug for templates
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.engine('pug', pug.renderFile)
// Pretty print JSON
app.set('json spaces', 2)
// Use GZIP
app.use(compress())
app.use(function (req, res, next) {
// Force SSL
if (config.isProd && req.protocol !== 'https') {
return res.redirect('https://' + (req.hostname || 'instant.io') + req.url)
}
// Redirect www to non-www
if (config.isProd && req.hostname === 'www.instant.io') {
return res.redirect('https://instant.io' + req.url)
}
// Use HTTP Strict Transport Security
// Lasts 1 year, incl. subdomains, allow browser preload list
if (config.isProd) {
res.header(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload'
)
}
// Add cross-domain header for fonts, required by spec, Firefox, and IE.
var extname = path.extname(url.parse(req.url).pathname)
if (['.eot', '.ttf', '.otf', '.woff', '.woff2'].indexOf(extname) >= 0) {
res.header('Access-Control-Allow-Origin', '*')
}
// Prevents IE and Chrome from MIME-sniffing a response. Reduces exposure to
// drive-by download attacks on sites serving user uploaded content.
res.header('X-Content-Type-Options', 'nosniff')
// Prevent rendering of site within a frame.
res.header('X-Frame-Options', 'DENY')
// Enable the XSS filter built into most recent web browsers. It's usually
// enabled by default anyway, so role of this headers is to re-enable for this
// particular website if it was disabled by the user.
res.header('X-XSS-Protection', '1; mode=block')
// Force IE to use latest rendering engine or Chrome Frame
res.header('X-UA-Compatible', 'IE=Edge,chrome=1')
next()
})
app.use(express.static(path.join(__dirname, '../static')))
app.get('/', function (req, res) {
res.render('index', {
title: 'Instant.io - Streaming file transfer over WebTorrent'
})
})
// Fetch new iceServers from twilio token regularly
var iceServers
var twilioClient
try {
twilioClient = twilio(secret.twilio.accountSid, secret.twilio.authToken)
} catch (err) {}
function updateIceServers () {
twilioClient.tokens.create({}, function (err, token) {
if (err) return console.error(err.message || err)
if (!token.iceServers) {
return console.error('twilio response ' + util.inspect(token) + ' missing iceServers')
}
// Support new spec (`RTCIceServer.url` was renamed to `RTCIceServer.urls`)
iceServers = token.iceServers.map(function (server) {
if (server.url != null) {
server.urls = server.url
delete server.url
}
return server
})
})
}
if (twilioClient) {
setInterval(updateIceServers, 60 * 60 * 4 * 1000).unref()
updateIceServers()
}
// WARNING: This is *NOT* a public endpoint. Do not depend on it in your app.
app.get('/_rtcConfig', cors({
origin: function (origin, cb) {
var allowed = CORS_WHITELIST.indexOf(origin) >= 0 ||
/https?:\/\/localhost(:|$)/.test(origin) ||
/https?:\/\/[^./]+\.localtunnel\.me$/.test(origin)
cb(null, allowed)
}
}), function (req, res) {
if (!iceServers) return res.status(404).send({ iceServers: [] })
res.send({
comment: 'WARNING: This is *NOT* a public endpoint. Do not depend on it in your app',
iceServers: iceServers
})
})
app.get('/500', (req, res, next) => {
next(new Error('Manually visited /500'))
})
app.get('*', function (req, res) {
res.status(404).render('error', {
title: '404 Page Not Found - Instant.io',
message: '404 Not Found'
})
})
// error handling middleware
app.use(function (err, req, res, next) {
console.error(err.stack)
const code = typeof err.code === 'number' ? err.code : 500
res.status(code).render('error', {
title: '500 Internal Server Error - Instant.io',
message: err.message || err
})
})
server.listen(PORT, function () {
console.log('listening on port %s', server.address().port)
})
|
server/index.js
|
var compress = require('compression')
var cors = require('cors')
var express = require('express')
var http = require('http')
var pug = require('pug')
var path = require('path')
var twilio = require('twilio')
var url = require('url')
var util = require('util')
var config = require('../config')
var PORT = Number(process.argv[2]) || 4000
var CORS_WHITELIST = [
// Official WebTorrent site
'http://webtorrent.io',
'https://webtorrent.io',
// Favor to friends :)
'http://rollcall.audio',
'https://rollcall.audio',
// Conference talk
'http://nordicjs.fun',
'https://nordicjs.fun'
]
var secret
try {
secret = require('../secret')
} catch (err) {}
var app = express()
var server = http.createServer(app)
// Trust "X-Forwarded-For" and "X-Forwarded-Proto" nginx headers
app.enable('trust proxy')
// Disable "powered by express" header
app.set('x-powered-by', false)
// Use pug for templates
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.engine('pug', pug.renderFile)
// Pretty print JSON
app.set('json spaces', 2)
// Use GZIP
app.use(compress())
app.use(function (req, res, next) {
// Force SSL
if (config.isProd && req.protocol !== 'https') {
return res.redirect('https://' + (req.hostname || 'instant.io') + req.url)
}
// Redirect www to non-www
if (config.isProd && req.hostname === 'www.instant.io') {
return res.redirect('https://instant.io' + req.url)
}
// Use HTTP Strict Transport Security
// Lasts 1 year, incl. subdomains, allow browser preload list
if (config.isProd) {
res.header(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload'
)
}
// Add cross-domain header for fonts, required by spec, Firefox, and IE.
var extname = path.extname(url.parse(req.url).pathname)
if (['.eot', '.ttf', '.otf', '.woff', '.woff2'].indexOf(extname) >= 0) {
res.header('Access-Control-Allow-Origin', '*')
}
// Prevents IE and Chrome from MIME-sniffing a response. Reduces exposure to
// drive-by download attacks on sites serving user uploaded content.
res.header('X-Content-Type-Options', 'nosniff')
// Prevent rendering of site within a frame.
res.header('X-Frame-Options', 'DENY')
// Enable the XSS filter built into most recent web browsers. It's usually
// enabled by default anyway, so role of this headers is to re-enable for this
// particular website if it was disabled by the user.
res.header('X-XSS-Protection', '1; mode=block')
// Force IE to use latest rendering engine or Chrome Frame
res.header('X-UA-Compatible', 'IE=Edge,chrome=1')
next()
})
app.use(express.static(path.join(__dirname, '../static')))
app.get('/', function (req, res) {
res.render('index', {
title: 'Instant.io - Streaming file transfer over WebTorrent'
})
})
// Fetch new iceServers from twilio token regularly
var iceServers
var twilioClient
try {
twilioClient = twilio(secret.twilio.accountSid, secret.twilio.authToken)
} catch (err) {}
function updateIceServers () {
twilioClient.tokens.create({}, function (err, token) {
if (err) return console.error(err.message || err)
if (!token.iceServers) {
return console.error('twilio response ' + util.inspect(token) + ' missing iceServers')
}
// Support new spec (`RTCIceServer.url` was renamed to `RTCIceServer.urls`)
iceServers = token.iceServers.map(function (server) {
if (server.url != null) {
server.urls = server.url
delete server.url
}
return server
})
})
}
if (twilioClient) {
setInterval(updateIceServers, 60 * 60 * 4 * 1000).unref()
updateIceServers()
}
// WARNING: This is *NOT* a public endpoint. Do not depend on it in your app.
app.get('/_rtcConfig', cors({
origin: function (origin, cb) {
var allowed = CORS_WHITELIST.indexOf(origin) >= 0 ||
/https?:\/\/localhost(:|$)/.test(origin) ||
/https?:\/\/[^./]+\.localtunnel\.me$/.test(origin)
cb(null, allowed)
}
}), function (req, res) {
if (!iceServers) return res.status(404).send({ iceServers: [] })
res.send({
comment: 'WARNING: This is *NOT* a public endpoint. Do not depend on it in your app',
iceServers: iceServers
})
})
app.get('/500', (req, res, next) => {
next(new Error('Manually visited /500'))
})
app.get('*', function (req, res) {
res.status(404).render('error', {
title: '404 Page Not Found - Instant.io',
message: '404 Not Found'
})
})
// error handling middleware
app.use(function (err, req, res, next) {
console.error(err.stack)
const code = typeof err.code === 'number' ? err.code : 500
res.status(code).render('error', {
title: '500 Internal Server Error - Instant.io',
message: err.message || err
})
})
server.listen(PORT, function () {
console.log('listening on port %s', server.address().port)
})
|
remove conference talk cors header
|
server/index.js
|
remove conference talk cors header
|
<ide><path>erver/index.js
<ide>
<ide> // Favor to friends :)
<ide> 'http://rollcall.audio',
<del> 'https://rollcall.audio',
<del>
<del> // Conference talk
<del> 'http://nordicjs.fun',
<del> 'https://nordicjs.fun'
<add> 'https://rollcall.audio'
<ide> ]
<ide>
<ide> var secret
|
|
Java
|
apache-2.0
|
adb102f250e537827ce3c901bdae423ece76b81a
| 0 |
raphw/byte-buddy,raphw/byte-buddy,raphw/byte-buddy
|
package net.bytebuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.TypeResolutionStrategy;
import net.bytebuddy.dynamic.loading.ByteArrayClassLoader;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.StubMethod;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.test.utility.DebuggingWrapper;
import net.bytebuddy.test.utility.JavaVersionRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
import static net.bytebuddy.matcher.ElementMatchers.isTypeInitializer;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class ByteBuddyTest {
@Rule
public JavaVersionRule javaVersionRule = new JavaVersionRule();
@Test(expected = IllegalArgumentException.class)
public void testEnumWithoutValuesIsIllegal() throws Exception {
new ByteBuddy().makeEnumeration();
}
@Test
public void testEnumeration() throws Exception {
Class<?> type = new ByteBuddy()
.makeEnumeration("foo")
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(Modifier.isPublic(type.getModifiers()), is(true));
assertThat(type.isEnum(), is(true));
assertThat(type.isInterface(), is(false));
assertThat(type.isAnnotation(), is(false));
}
@Test
public void testInterface() throws Exception {
Class<?> type = new ByteBuddy()
.makeInterface()
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(Modifier.isPublic(type.getModifiers()), is(true));
assertThat(type.isEnum(), is(false));
assertThat(type.isInterface(), is(true));
assertThat(type.isAnnotation(), is(false));
}
@Test
public void testAnnotation() throws Exception {
Class<?> type = new ByteBuddy()
.makeAnnotation()
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(Modifier.isPublic(type.getModifiers()), is(true));
assertThat(type.isEnum(), is(false));
assertThat(type.isInterface(), is(true));
assertThat(type.isAnnotation(), is(true));
}
@Test
@JavaVersionRule.Enforce(16)
public void testRecordWithoutMember() throws Exception {
Class<?> type = new ByteBuddy()
.with(ClassFileVersion.JAVA_V16)
.makeRecord()
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat((Boolean) Class.class.getMethod("isRecord").invoke(type), is(true));
Object record = type.getConstructor().newInstance();
assertThat(type.getMethod("hashCode").invoke(record), is((Object) 0));
assertThat(type.getMethod("equals", Object.class).invoke(record, new Object()), is((Object) false));
assertThat(type.getMethod("equals", Object.class).invoke(record, record), is((Object) true));
assertThat(type.getMethod("toString").invoke(record), is((Object) (type.getSimpleName() + "[]")));
}
@Test
@JavaVersionRule.Enforce(16)
public void testRecordWithMember() throws Exception {
Class<?> type = new ByteBuddy()
.with(ClassFileVersion.JAVA_V16)
.makeRecord()
.defineRecordComponent("foo", String.class)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat((Boolean) Class.class.getMethod("isRecord").invoke(type), is(true));
Object record = type.getConstructor(String.class).newInstance("bar");
assertThat(type.getMethod("foo").invoke(record), is((Object) "bar"));
assertThat(type.getMethod("hashCode").invoke(record), is((Object) "bar".hashCode()));
assertThat(type.getMethod("equals", Object.class).invoke(record, new Object()), is((Object) false));
assertThat(type.getMethod("equals", Object.class).invoke(record, record), is((Object) true));
assertThat(type.getMethod("toString").invoke(record), is((Object) (type.getSimpleName() + "[foo=bar]")));
}
@Test
public void testTypeInitializerInstrumentation() throws Exception {
Recorder recorder = new Recorder();
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.invokable(isTypeInitializer())
.intercept(MethodDelegation.to(recorder))
.make(new TypeResolutionStrategy.Active())
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(type.getDeclaredConstructor().newInstance(), instanceOf(type));
assertThat(recorder.counter, is(1));
}
@Test
public void testImplicitStrategyBootstrap() throws Exception {
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER)
.getLoaded();
assertThat(type.getClassLoader(), notNullValue(ClassLoader.class));
}
@Test
public void testImplicitStrategyNonBootstrap() throws Exception {
ClassLoader classLoader = new URLClassLoader(new URL[0], ClassLoadingStrategy.BOOTSTRAP_LOADER);
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(classLoader)
.getLoaded();
assertThat(type.getClassLoader(), not(classLoader));
}
@Test
public void testImplicitStrategyInjectable() throws Exception {
ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, false, Collections.<String, byte[]>emptyMap());
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(classLoader)
.getLoaded();
assertThat(type.getClassLoader(), is(classLoader));
}
@Test
public void testClassWithManyMethods() throws Exception {
DynamicType.Builder<?> builder = new ByteBuddy().subclass(Object.class);
for (int index = 0; index < 1000; index++) {
builder = builder.defineMethod("method" + index, void.class, Visibility.PUBLIC).intercept(StubMethod.INSTANCE);
}
Class<?> type = builder.make().load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
assertThat(type.getDeclaredMethods().length, is(1000));
DynamicType.Builder<?> subclassBuilder = new ByteBuddy().subclass(type);
for (Method method : type.getDeclaredMethods()) {
subclassBuilder = subclassBuilder.method(ElementMatchers.is(method)).intercept(StubMethod.INSTANCE);
}
Class<?> subclass = subclassBuilder.make().load(type.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
assertThat(subclass.getDeclaredMethods().length, is(1000));
}
@Test
public void testClassCompiledToJsr14() throws Exception {
assertThat(new ByteBuddy()
.redefine(Class.forName("net.bytebuddy.test.precompiled.Jsr14Sample"))
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.getConstructor()
.newInstance(), notNullValue());
}
public static class Recorder {
public int counter;
public void instrument() {
counter++;
}
}
}
|
byte-buddy-dep/src/test/java/net/bytebuddy/ByteBuddyTest.java
|
package net.bytebuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.TypeResolutionStrategy;
import net.bytebuddy.dynamic.loading.ByteArrayClassLoader;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.StubMethod;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.test.utility.DebuggingWrapper;
import net.bytebuddy.test.utility.JavaVersionRule;
import org.junit.Ignore;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
import static net.bytebuddy.matcher.ElementMatchers.isTypeInitializer;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class ByteBuddyTest {
@Test(expected = IllegalArgumentException.class)
public void testEnumWithoutValuesIsIllegal() throws Exception {
new ByteBuddy().makeEnumeration();
}
@Test
public void testEnumeration() throws Exception {
Class<?> type = new ByteBuddy()
.makeEnumeration("foo")
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(Modifier.isPublic(type.getModifiers()), is(true));
assertThat(type.isEnum(), is(true));
assertThat(type.isInterface(), is(false));
assertThat(type.isAnnotation(), is(false));
}
@Test
public void testInterface() throws Exception {
Class<?> type = new ByteBuddy()
.makeInterface()
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(Modifier.isPublic(type.getModifiers()), is(true));
assertThat(type.isEnum(), is(false));
assertThat(type.isInterface(), is(true));
assertThat(type.isAnnotation(), is(false));
}
@Test
public void testAnnotation() throws Exception {
Class<?> type = new ByteBuddy()
.makeAnnotation()
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(Modifier.isPublic(type.getModifiers()), is(true));
assertThat(type.isEnum(), is(false));
assertThat(type.isInterface(), is(true));
assertThat(type.isAnnotation(), is(true));
}
@Test
@JavaVersionRule.Enforce(16)
public void testRecordWithoutMember() throws Exception {
Class<?> type = new ByteBuddy()
.with(ClassFileVersion.JAVA_V16)
.makeRecord()
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat((Boolean) Class.class.getMethod("isRecord").invoke(type), is(true));
Object record = type.getConstructor().newInstance();
assertThat(type.getMethod("hashCode").invoke(record), is((Object) 0));
assertThat(type.getMethod("equals", Object.class).invoke(record, new Object()), is((Object) false));
assertThat(type.getMethod("equals", Object.class).invoke(record, record), is((Object) true));
assertThat(type.getMethod("toString").invoke(record), is((Object) (type.getSimpleName() + "[]")));
}
@Test
@JavaVersionRule.Enforce(16)
public void testRecordWithMember() throws Exception {
Class<?> type = new ByteBuddy()
.with(ClassFileVersion.JAVA_V16)
.makeRecord()
.defineRecordComponent("foo", String.class)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat((Boolean) Class.class.getMethod("isRecord").invoke(type), is(true));
Object record = type.getConstructor(String.class).newInstance("bar");
assertThat(type.getMethod("foo").invoke(record), is((Object) "bar"));
assertThat(type.getMethod("hashCode").invoke(record), is((Object) "bar".hashCode()));
assertThat(type.getMethod("equals", Object.class).invoke(record, new Object()), is((Object) false));
assertThat(type.getMethod("equals", Object.class).invoke(record, record), is((Object) true));
assertThat(type.getMethod("toString").invoke(record), is((Object) (type.getSimpleName() + "[foo=bar]")));
}
@Test
public void testTypeInitializerInstrumentation() throws Exception {
Recorder recorder = new Recorder();
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.invokable(isTypeInitializer())
.intercept(MethodDelegation.to(recorder))
.make(new TypeResolutionStrategy.Active())
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(type.getDeclaredConstructor().newInstance(), instanceOf(type));
assertThat(recorder.counter, is(1));
}
@Test
public void testImplicitStrategyBootstrap() throws Exception {
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER)
.getLoaded();
assertThat(type.getClassLoader(), notNullValue(ClassLoader.class));
}
@Test
public void testImplicitStrategyNonBootstrap() throws Exception {
ClassLoader classLoader = new URLClassLoader(new URL[0], ClassLoadingStrategy.BOOTSTRAP_LOADER);
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(classLoader)
.getLoaded();
assertThat(type.getClassLoader(), not(classLoader));
}
@Test
public void testImplicitStrategyInjectable() throws Exception {
ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, false, Collections.<String, byte[]>emptyMap());
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(classLoader)
.getLoaded();
assertThat(type.getClassLoader(), is(classLoader));
}
@Test
public void testClassWithManyMethods() throws Exception {
DynamicType.Builder<?> builder = new ByteBuddy().subclass(Object.class);
for (int index = 0; index < 1000; index++) {
builder = builder.defineMethod("method" + index, void.class, Visibility.PUBLIC).intercept(StubMethod.INSTANCE);
}
Class<?> type = builder.make().load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
assertThat(type.getDeclaredMethods().length, is(1000));
DynamicType.Builder<?> subclassBuilder = new ByteBuddy().subclass(type);
for (Method method : type.getDeclaredMethods()) {
subclassBuilder = subclassBuilder.method(ElementMatchers.is(method)).intercept(StubMethod.INSTANCE);
}
Class<?> subclass = subclassBuilder.make().load(type.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
assertThat(subclass.getDeclaredMethods().length, is(1000));
}
@Test
public void testClassCompiledToJsr14() throws Exception {
assertThat(new ByteBuddy()
.redefine(Class.forName("net.bytebuddy.test.precompiled.Jsr14Sample"))
.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.getConstructor()
.newInstance(), notNullValue());
}
public static class Recorder {
public int counter;
public void instrument() {
counter++;
}
}
}
|
Add rule for Java version discrimination.
|
byte-buddy-dep/src/test/java/net/bytebuddy/ByteBuddyTest.java
|
Add rule for Java version discrimination.
|
<ide><path>yte-buddy-dep/src/test/java/net/bytebuddy/ByteBuddyTest.java
<ide> import net.bytebuddy.test.utility.DebuggingWrapper;
<ide> import net.bytebuddy.test.utility.JavaVersionRule;
<ide> import org.junit.Ignore;
<add>import org.junit.Rule;
<ide> import org.junit.Test;
<ide>
<ide> import java.lang.reflect.Method;
<ide> import static org.hamcrest.MatcherAssert.assertThat;
<ide>
<ide> public class ByteBuddyTest {
<add>
<add> @Rule
<add> public JavaVersionRule javaVersionRule = new JavaVersionRule();
<ide>
<ide> @Test(expected = IllegalArgumentException.class)
<ide> public void testEnumWithoutValuesIsIllegal() throws Exception {
|
|
JavaScript
|
mit
|
1e87a15f79df10877a69f875649457a3fecabc55
| 0 |
hoge1e3/Tonyu2,hoge1e3/Tonyu2,hoge1e3/Tonyu2,hoge1e3/Tonyu2
|
if (typeof define!=="function") {//B
define=require("requirejs").define;
}
define(["Tonyu", "Tonyu.Iterator", "TonyuLang", "ObjectMatcher", "TError", "IndentBuffer",
"context", "Visitor","Tonyu.Compiler"],
function(Tonyu, Tonyu_iterator, TonyuLang, ObjectMatcher, TError, IndentBuffer,
context, Visitor,cu) {
return cu.JSGenerator=(function () {
// TonyuソースファイルをJavascriptに変換する
var TH="_thread",THIZ="_this", ARGS="_arguments",FIBPRE="fiber$", FRMPC="__pc", LASTPOS="$LASTPOS",CNTV="__cnt",CNTC=100;//G
var BINDF="Tonyu.bindFunc";
var INVOKE_FUNC="Tonyu.invokeMethod";
var CALL_FUNC="Tonyu.callFunc";
var CHK_NN="Tonyu.checkNonNull";
var CLASS_HEAD="Tonyu.classes.", GLOBAL_HEAD="Tonyu.globals.";
var GET_THIS="this.isTonyuObject?this:Tonyu.not_a_tonyu_object(this)";
var ITER="Tonyu.iterator";
/*var ScopeTypes={FIELD:"field", METHOD:"method", NATIVE:"native",//B
LOCAL:"local", THVAR:"threadvar", PARAM:"param", GLOBAL:"global", CLASS:"class"};*/
var ScopeTypes=cu.ScopeTypes;
//var genSt=cu.newScopeType;
var stype=cu.getScopeType;
//var newScope=cu.newScope;
//var nc=cu.nullCheck;
//var genSym=cu.genSym;
var annotation3=cu.annotation;
var getMethod2=cu.getMethod;
var getDependingClasses=cu.getDependingClasses;
var getParams=cu.getParams;
//-----------
function genJS(klass, env) {//B
var srcFile=klass.src.tonyu; //file object //S
var srcCont=srcFile.text();
function getSource(node) {
return cu.getSource(srcCont,node);
}
var buf=IndentBuffer();
var printf=buf.printf;
var ctx=context();
var debug=false;
var OM=ObjectMatcher;
var traceTbl=env.traceTbl;
// method := fiber | function
var decls=klass.decls;
var fields=decls.fields,
methods=decls.methods,
natives=decls.natives;
// ↑ このクラスが持つフィールド,ファイバ,関数,ネイティブ変数の集まり.親クラスの宣言は含まない
var ST=ScopeTypes;
var fnSeq=0;
var diagnose=env.options.compiler.diagnose;
function annotation(node, aobj) {//B
return annotation3(klass.annotation,node,aobj);
}
function getMethod(name) {//B
return getMethod2(klass,name);
}
function getClassName(klass){// should be object or short name //G
if (typeof klass=="string") return CLASS_HEAD+(env.aliases[klass] || klass);//CFN CLASS_HEAD+env.aliases[klass](null check)
if (klass.builtin) return klass.fullName;// CFN klass.fullName
return CLASS_HEAD+klass.fullName;// CFN klass.fullName
}
function getClassNames(cs){//G
var res=[];
cs.forEach(function (c) { res.push(getClassName(c)); });
return res;
}
function enterV(obj, node) {//G
return function (buf) {
ctx.enter(obj,function () {
v.visit(node);
});
};
}
function varAccess(n, si, an) {//G
var t=stype(si);
if (t==ST.THVAR) {
buf.printf("%s",TH);
} else if (t==ST.FIELD) {
buf.printf("%s.%s",THIZ, n);
} else if (t==ST.METHOD) {
if (an && an.noBind) {
buf.printf("%s.%s",THIZ, n);
} else {
buf.printf("%s(%s,%s.%s)",BINDF, THIZ, THIZ, n);
}
} else if (t==ST.CLASS) {
buf.printf("%s",getClassName(n));
} else if (t==ST.GLOBAL) {
buf.printf("%s%s",GLOBAL_HEAD, n);
} else if (t==ST.PARAM || t==ST.LOCAL || t==ST.NATIVE) {
buf.printf("%s",n);
} else {
console.log("Unknown scope type: ",t);
throw new Error("Unknown scope type: "+t);
}
return si;
}
function noSurroundCompoundF(node) {//G
return function () {
noSurroundCompound.apply(this, [node]);
};
}
function noSurroundCompound(node) {//G
if (node.type=="compound") {
ctx.enter({noWait:true},function () {
buf.printf("%j%n", ["%n",node.stmts]);
// buf.printf("%{%j%n%}", ["%n",node.stmts]);
});
} else {
v.visit(node);
}
}
function lastPosF(node) {//G
return function () {
buf.printf("%s%s=%s;//%s%n", (env.options.compiler.commentLastPos?"//":""),
LASTPOS, traceTbl.add(klass/*.src.tonyu*/,node.pos ), klass.fullName+":"+node.pos);
};
}
var THNode={type:"THNode"};//G
v=buf.visitor=Visitor({//G
THNode: function (node) {
buf.printf(TH);
},
dummy: function (node) {
buf.printf("",node);
},
literal: function (node) {
buf.printf("%s",node.text);
},
paramDecl: function (node) {
buf.printf("%v",node.name);
},
paramDecls: function (node) {
buf.printf("(%j)",[", ",node.params]);
},
funcDeclHead: function (node) {
buf.printf("function %v %v",node.name, node.params);
},
funcDecl: function (node) {
},
"return": function (node) {
if (ctx.inTry) throw TError("現実装では、tryの中にreturnは書けません",srcFile,node.pos);
if (!ctx.noWait) {
if (node.value) {
buf.printf("%s.exit(%v);return;",TH,node.value);
} else {
buf.printf("%s.exit(%s);return;",TH,THIZ);
}
} else {
if (ctx.threadAvail) {
if (node.value) {
buf.printf("%s.retVal=%v;return;%n",TH, node.value);
} else {
buf.printf("%s.retVal=%s;return;%n",TH, THIZ);
}
} else {
if (node.value) {
buf.printf("return %v;",node.value);
} else {
buf.printf("return %s;",THIZ);
}
}
}
},
program: function (node) {
genClass(node.stmts);
},
number: function (node) {
buf.printf("%s", node.value );
},
reservedConst: function (node) {
if (node.text=="this") {
buf.printf("%s",THIZ);
} else if (node.text=="arguments" && ctx.threadAvail) {
buf.printf("%s",ARGS);
} else if (node.text==TH) {
buf.printf("%s", (ctx.threadAvail)?TH:"null");
} else {
buf.printf("%s", node.text);
}
},
varDecl: function (node) {
if (node.value) {
buf.printf("%v = %v", node.name, node.value );
} else {
buf.printf("%v", node.name);
}
},
varsDecl: function (node) {
lastPosF(node)();
buf.printf("%j;", [";",node.decls]);
},
jsonElem: function (node) {
if (node.value) {
buf.printf("%v: %v", node.key, node.value);
} else {
buf.printf("%v: %f", node.key, function () {
var si=varAccess( node.key.text, annotation(node).scopeInfo, annotation(node));
});
}
},
objlit: function (node) {
buf.printf("{%j}", [",", node.elems]);
},
arylit: function (node) {
buf.printf("[%j]", [",", node.elems]);
},
funcExpr: function (node) {
genFuncExpr(node);
},
parenExpr: function (node) {
buf.printf("(%v)",node.expr);
},
varAccess: function (node) {
var n=node.name.text;
var si=varAccess(n,annotation(node).scopeInfo, annotation(node));
},
exprstmt: function (node) {//exprStmt
var t={};
lastPosF(node)();
if (!ctx.noWait) {
t=annotation(node).fiberCall || {};
}
if (t.type=="noRet") {
buf.printf(
"%s.%s%s(%j);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{",
THIZ, FIBPRE, t.N, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++
);
} else if (t.type=="ret") {
buf.printf(
"%s.%s%s(%j);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{"+
"%v%v%s.retVal;%n",
THIZ, FIBPRE, t.N, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++,
t.L, t.O, TH
);
} else if (t.type=="noRetSuper") {
var p=getClassName(klass.superclass);
buf.printf(
"%s.prototype.%s%s.apply( %s, [%j]);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{",
p, FIBPRE, t.S.name.text, THIZ, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++
);
} else if (t.type=="retSuper") {
buf.printf(
"%s.prototype.%s%s.apply( %s, [%j]);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{"+
"%v%v%s.retVal;%n",
p, FIBPRE, t.S.name.text, THIZ, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++,
t.L, t.O, TH
);
} else {
buf.printf("%v;", node.expr );
}
},
infix: function (node) {
var opn=node.op.text;
/*if (opn=="=" || opn=="+=" || opn=="-=" || opn=="*=" || opn=="/=" || opn=="%=" ) {
checkLVal(node.left);
}*/
if (diagnose) {
if (opn=="+" || opn=="-" || opn=="*" || opn=="/" || opn=="%" ) {
buf.printf("%s(%v,%l)%v%s(%v,%l)", CHK_NN, node.left, getSource(node.left), node.op,
CHK_NN, node.right, getSource(node.right));
return;
}
if (opn=="+=" || opn=="-=" || opn=="*=" || opn=="/=" || opn=="%=" ) {
buf.printf("%v%v%s(%v,%l)", node.left, node.op,
CHK_NN, node.right, getSource(node.right));
return;
}
}
buf.printf("%v%v%v", node.left, node.op, node.right);
},
trifixr:function (node) {
buf.printf("%v%v%v%v%v", node.left, node.op1, node.mid, node.op2, node.right);
},
prefix: function (node) {
buf.printf("%v %v", node.op, node.right);
},
postfix: function (node) {
var a=annotation(node);
if (diagnose) {
if (a.myMethodCall) {
var mc=a.myMethodCall;
var si=mc.scopeInfo;
var st=stype(si);
if (st==ST.FIELD || st==ST.METHOD) {
buf.printf("%s(%s, %l, [%j], %l )", INVOKE_FUNC,THIZ, mc.name, [",",mc.args],"this");
} else {
buf.printf("%s(%v, [%j], %l)", CALL_FUNC, node.left, [",",mc.args], getSource(node.left));
}
return;
} else if (a.othersMethodCall) {
var oc=a.othersMethodCall;
buf.printf("%s(%v, %l, [%j], %l )", INVOKE_FUNC, oc.target, oc.name, [",",oc.args],getSource(oc.target));
return;
} else if (a.memberAccess) {
var ma=a.memberAccess;
buf.printf("%s(%v,%l).%s", CHK_NN, ma.target, getSource(ma.target), ma.name );
return;
}
} else if (a.myMethodCall) {
var mc=a.myMethodCall;
var si=mc.scopeInfo;
var st=stype(si);
if (st==ST.METHOD) {
buf.printf("%s.%s(%j)",THIZ, mc.name, [",",mc.args]);
return;
}
}
buf.printf("%v%v", node.left, node.op);
},
"break": function (node) {
if (!ctx.noWait) {
if (ctx.inTry && ctx.exitTryOnJump) throw TError("現実装では、tryの中にbreak;は書けません",srcFile,node.pos);
if (ctx.closestBrk) {
buf.printf("%s=%z; break;%n", FRMPC, ctx.closestBrk);
} else {
throw TError( "break; は繰り返しの中で使います" , srcFile, node.pos);
}
} else {
buf.printf("break;%n");
}
},
"try": function (node) {
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasJump || an.hasReturn)) {
//buf.printf("/*try catch in wait mode is not yet supported*/%n");
if (node.catches.length!=1 || node.catches[0].type!="catch") {
throw TError("現実装では、catch節1個のみをサポートしています",srcFile,node.pos);
}
var ct=node.catches[0];
var catchPos={},finPos={};
buf.printf("%s.enterTry(%z);%n",TH,catchPos);
buf.printf("%f", enterV({inTry:true, exitTryOnJump:true},node.stmt) );
buf.printf("%s.exitTry();%n",TH);
buf.printf("%s=%z;break;%n",FRMPC,finPos);
buf.printf("%}case %f:%{",function (){
buf.print(catchPos.put(ctx.pc++));
});
buf.printf("%s=%s.startCatch();%n",ct.name.text, TH);
buf.printf("%s.exitTry();%n",TH);
buf.printf("%v%n", ct.stmt);
buf.printf("%}case %f:%{",function (){
buf.print(finPos.put(ctx.pc++));
});
} else {
ctx.enter({noWait:true}, function () {
buf.printf("try {%{%f%n%}} ",
noSurroundCompoundF(node.stmt));
node.catches.forEach(v.visit);
});
}
},
"catch": function (node) {
buf.printf("catch (%s) {%{%f%n%}}",node.name.text, noSurroundCompoundF(node.stmt));
},
"throw": function (node) {
buf.printf("throw %v;%n",node.ex);
},
"while": function (node) {
lastPosF(node)();
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasReturn)) {
var brkpos=buf.lazy();
var pc=ctx.pc++;
var isTrue= node.cond.type=="reservedConst" && node.cond.text=="true";
buf.printf(
/*B*/
"%}case %d:%{" +
(isTrue?"%D%D%D":"if (!(%v)) { %s=%z; break; }%n") +
"%f%n" +
"%s=%s;break;%n" +
"%}case %f:%{",
pc,
node.cond, FRMPC, brkpos,
enterV({closestBrk:brkpos, exitTryOnJump:false}, node.loop),
FRMPC, pc,
function () { buf.print(brkpos.put(ctx.pc++)); }
);
} else {
ctx.enter({noWait:true},function () {
buf.printf("while (%v) {%{%f%n%}}", node.cond, noSurroundCompoundF(node.loop));
});
}
},
"for": function (node) {
lastPosF(node)();
var an=annotation(node);
if (node.inFor.type=="forin") {
var itn=annotation(node.inFor).iterName;
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasReturn)) {
var brkpos=buf.lazy();
var pc=ctx.pc++;
buf.printf(
"%s=%s(%v,%s);%n"+
"%}case %d:%{" +
"if (!(%s.next())) { %s=%z; break; }%n" +
"%f%n" +
"%f%n" +
"%s=%s;break;%n" +
"%}case %f:%{",
itn, ITER, node.inFor.set, node.inFor.vars.length,
pc,
itn, FRMPC, brkpos,
getElemF(itn, node.inFor.isVar, node.inFor.vars),
enterV({closestBrk:brkpos, exitTryOnJump:false}, node.loop),//node.loop,
FRMPC, pc,
function (buf) { buf.print(brkpos.put(ctx.pc++)); }
);
} else {
ctx.enter({noWait:true},function() {
buf.printf(
"%s=%s(%v,%s);%n"+
"while(%s.next()) {%{" +
"%f%n"+
"%f%n" +
"%}}",
itn, ITER, node.inFor.set, node.inFor.vars.length,
itn,
getElemF(itn, node.inFor.isVar, node.inFor.vars),
noSurroundCompoundF(node.loop)
);
});
}
} else {
if (!ctx.noWait&&
(an.fiberCallRequired || an.hasReturn)) {
var brkpos=buf.lazy();
var pc=ctx.pc++;
buf.printf(
"%v;%n"+
"%}case %d:%{" +
"if (!(%v)) { %s=%z; break; }%n" +
"%f%n" +
"%v;%n" +
"%s=%s;break;%n" +
"%}case %f:%{",
node.inFor.init ,
pc,
node.inFor.cond, FRMPC, brkpos,
enterV({closestBrk:brkpos,exitTryOnJump:false}, node.loop),//node.loop,
node.inFor.next,
FRMPC, pc,
function (buf) { buf.print(brkpos.put(ctx.pc++)); }
);
} else {
ctx.enter({noWait:true},function() {
buf.printf(
"%v%n"+
"while(%v) {%{" +
"%v%n" +
"%v;%n" +
"%}}",
node.inFor.init ,
node.inFor.cond,
node.loop,
node.inFor.next
);
});
}
}
function getElemF(itn, isVar, vars) {
return function () {
vars.forEach(function (v,i) {
buf.printf("%s=%s[%s];%n", v.text, itn, i);
});
};
}
},
"if": function (node) {
lastPosF(node)();
//buf.printf("/*FBR=%s*/",!!annotation(node).fiberCallRequired);
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasJump || an.hasReturn)) {
var fipos={}, elpos={};
if (node._else) {
buf.printf(
"if (!(%v)) { %s=%z; break; }%n" +
"%v%n" +
"%s=%z;break;%n" +
"%}case %f:%{" +
"%v%n" +
/*B*/
"%}case %f:%{" ,
node.cond, FRMPC, elpos,
node.then,
FRMPC, fipos,
function () { buf.print(elpos.put(ctx.pc++)); },
node._else,
function () { buf.print(fipos.put(ctx.pc++)); }
);
} else {
buf.printf(
"if (!(%v)) { %s=%z; break; }%n" +
"%v%n" +
/*B*/
"%}case %f:%{",
node.cond, FRMPC, fipos,
node.then,
function () { buf.print(fipos.put(ctx.pc++)); }
);
}
} else {
ctx.enter({noWait:true}, function () {
if (node._else) {
buf.printf("if (%v) {%{%f%n%}} else {%{%f%n%}}", node.cond,
noSurroundCompoundF(node.then),
noSurroundCompoundF(node._else));
} else {
buf.printf("if (%v) {%{%f%n%}}", node.cond,
noSurroundCompoundF(node.then));
}
});
}
},
ifWait: function (node) {
if (!ctx.noWait) {
buf.printf("%v",node.then);
} else {
if (node._else) {
buf.printf("%v",node._else);
}
}
},
call: function (node) {
buf.printf("(%j)", [",",node.args]);
},
objlitArg: function (node) {
buf.printf("%v",node.obj);
},
argList: function (node) {
buf.printf("%j",[",",node.args]);
},
newExpr: function (node) {
var p=node.params;
if (p) {
buf.printf("new %v%v",node.klass,p);
} else {
buf.printf("new %v",node.klass);
}
},
scall: function (node) {
buf.printf("[%j]", [",",node.args]);
},
superExpr: function (node) {
var name;
if (!klass.superclass) throw new Error(klass.fullName+"には親クラスがありません");
if (node.name) {
name=node.name.text;
buf.printf("%s.prototype.%s.apply( %s, %v)",
getClassName(klass.superclass), name, THIZ, node.params);
} else {
buf.printf("%s.apply( %s, %v)",
getClassName(klass.superclass), THIZ, node.params);
}
},
arrayElem: function (node) {
buf.printf("[%v]",node.subscript);
},
member: function (node) {
buf.printf(".%v",node.name);
},
symbol: function (node) {
buf.print(node.text);
},
"normalFor": function (node) {
buf.printf("%v; %v; %v", node.init, node.cond, node.next);
},
compound: function (node) {
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasJump || an.hasReturn) ) {
buf.printf("%j", ["%n",node.stmts]);
} else {
/*if (ctx.noSurroundBrace) {
ctx.enter({noSurroundBrace:false,noWait:true},function () {
buf.printf("%{%j%n%}", ["%n",node.stmts]);
});
} else {*/
ctx.enter({noWait:true},function () {
buf.printf("{%{%j%n%}}", ["%n",node.stmts]);
});
//}
}
},
"typeof": function (node) {
buf.printf("typeof ");
},
"instanceof": function (node) {
buf.printf(" instanceof ");
},
"is": function (node) {
buf.printf(" instanceof ");
},
regex: function (node) {
buf.printf("%s",node.text);
}
});
var opTokens=["++", "--", "!==", "===", "+=", "-=", "*=", "/=",
"%=", ">=", "<=",
"!=", "==", ">>", "<<", "&&", "||", ">", "<", "+", "?", "=", "*",
"%", "/", "^", "~", "\\", ":", ";", ",", "!", "&", "|", "-"
,"delete" ];
opTokens.forEach(function (opt) {
v.funcs[opt]=function (node) {
buf.printf("%s",opt);
};
});
//v.debug=debug;
v.def=function (node) {
console.log("Err node=");
console.log(node);
throw node.type+" is not defined in visitor:compiler2";
};
v.cnt=0;
function genSource() {//G
/*if (env.options.compiler.asModule) {
klass.moduleName=getClassName(klass);
printf("if (typeof requireSimulator=='object') requireSimulator.setName(%l);%n",klass.moduleName);
printf("//requirejs(['Tonyu'%f],function (Tonyu) {%{", function (){
getDependingClasses(klass).forEach(function (k) {
printf(",%l",k.moduleName);
});
});
}*/
ctx.enter({}, function () {
var nspObj=CLASS_HEAD+klass.namespace;
printf("Tonyu.klass.ensureNamespace(%s,%l);%n",CLASS_HEAD.replace(/\.$/,""), klass.namespace);
if (klass.superclass) {
printf("%s=Tonyu.klass(%s,[%s],{%{",
getClassName(klass),
getClassName(klass.superclass),
getClassNames(klass.includes).join(","));
} else {
printf("%s=Tonyu.klass([%s],{%{",
getClassName(klass),
getClassNames(klass.includes).join(","));
}
//printf("Tonyu.klass.define({%{");
//printf("fullName:")
for (var name in methods) {
if (debug) console.log("method1", name);
var method=methods[name];
ctx.enter({noWait:true, threadAvail:false}, function () {
genFunc(method);
});
if (debug) console.log("method2", name);
if (!method.nowait ) {
ctx.enter({noWait:false,threadAvail:true}, function () {
genFiber(method);
});
}
if (debug) console.log("method3", name);
}
printf("__dummy: false%n");
printf("%}});%n");
});
printf("Tonyu.klass.addMeta(%s,%s);%n",
getClassName(klass),JSON.stringify(digestMeta(klass)));
//if (env.options.compiler.asModule) {
// printf("//%}});");
//}
}
function digestMeta(klass) {//G
var res={
fullName: klass.fullName,
namespace: klass.namespace,
shortName: klass.shortName,
decls:{methods:{}}
};
for (var i in klass.decls.methods) {
res.decls.methods[i]=
{nowait:!!klass.decls.methods[i].nowait};
}
return res;
}
function genFiber(fiber) {//G
if (isConstructor(fiber)) return;
var stmts=fiber.stmts;
var noWaitStmts=[], waitStmts=[], curStmts=noWaitStmts;
var opt=true;
if (opt) {
stmts.forEach(function (s) {
if (annotation(s).fiberCallRequired) {
curStmts=waitStmts;
}
curStmts.push(s);
});
} else {
waitStmts=stmts;
}
printf(
"%s%s :function %s(%j) {%{"+
"var %s=%s;%n"+
"%svar %s=%s;%n"+
"var %s=0;%n"+
"%f%n"+
"%f%n",
FIBPRE, fiber.name, genFn(fiber.pos,"f_"+fiber.name), [",",[THNode].concat(fiber.params)],
THIZ, GET_THIS,
(fiber.useArgs?"":"//"), ARGS, "Tonyu.A(arguments)",
FRMPC,
genLocalsF(fiber),
nfbody
);
if (waitStmts.length>0) {
printf(
"%s.enter(function %s(%s) {%{"+
"if (%s.lastEx) %s=%s.catchPC;%n"+
"for(var %s=%d ; %s--;) {%{"+
"switch (%s) {%{"+
"%}case 0:%{"+
"%f" +
"%s.exit(%s);return;%n"+
"%}}%n"+
"%}}%n"+
"%}});%n",
TH,genFn(fiber.pos,"ent_"+fiber.name),TH,
TH,FRMPC,TH,
CNTV, CNTC, CNTV,
FRMPC,
// case 0:
fbody,
TH,THIZ
);
} else {
printf("%s.retVal=%s;return;%n",TH,THIZ);
}
printf("%}},%n");
function nfbody() {
ctx.enter({method:fiber, /*scope: fiber.scope,*/ noWait:true, threadAvail:true }, function () {
noWaitStmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
function fbody() {
ctx.enter({method:fiber, /*scope: fiber.scope,*/
finfo:fiber, pc:1}, function () {
waitStmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genFunc(func) {//G
var fname= isConstructor(func) ? "initialize" : func.name;
printf("%s :function %s(%j) {%{"+
"var %s=%s;%n"+
"%f%n" +
"%f" +
"%}},%n",
fname, genFn(func.pos,fname), [",",func.params],
THIZ, GET_THIS,
genLocalsF(func),
fbody
);
function fbody() {
ctx.enter({method:func, finfo:func,
/*scope: func.scope*/ }, function () {
func.stmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genFuncExpr(node) {//G
var finfo=annotation(node);// annotateSubFuncExpr(node);
buf.printf("function (%j) {%{"+
"%f%n"+
"%f"+
"%}}"
,
[",", finfo.params],
genLocalsF(finfo),
fbody
);
function fbody() {
ctx.enter({noWait: true, threadAvail:false,
finfo:finfo, /*scope: finfo.scope*/ }, function () {
node.body.stmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genFn(pos,name) {//G
if (!name) name=(fnSeq++)+"";
return ("_trc_"+klass.shortName+"_"+name)
// return ("_trc_func_"+traceTbl.add(klass,pos )+"_"+(fnSeq++));// Math.random()).replace(/\./g,"");
}
function genSubFunc(node) {//G
var finfo=annotation(node);// annotateSubFuncExpr(node);
buf.printf("function %s(%j) {%{"+
"%f%n"+
"%f"+
"%}}"
,
finfo.name,[",", finfo.params],
genLocalsF(finfo),
fbody
);
function fbody() {
ctx.enter({noWait: true, threadAvail:false,
finfo:finfo, /*scope: finfo.scope*/ }, function () {
node.body.stmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genLocalsF(finfo) {//G
return f;
function f() {
ctx.enter({/*scope:finfo.scope*/}, function (){
for (var i in finfo.locals.varDecls) {
buf.printf("var %s;%n",i);
}
for (var i in finfo.locals.subFuncDecls) {
genSubFunc(finfo.locals.subFuncDecls[i]);
}
});
};
}
function isConstructor(f) {//G
return OM.match(f, {ftype:"constructor"}) || OM.match(f, {name:"new"});
}
genSource();//G
klass.src.js=buf.buf;//G
if (debug) {
console.log("method4", buf.buf);
//throw "ERR";
}
return buf.buf;
}//B
return {genJS:genJS};
})();
//if (typeof getReq=="function") getReq.exports("Tonyu.Compiler");
});
|
js/lang/JSGenerator.js
|
if (typeof define!=="function") {//B
define=require("requirejs").define;
}
define(["Tonyu", "Tonyu.Iterator", "TonyuLang", "ObjectMatcher", "TError", "IndentBuffer",
"context", "Visitor","Tonyu.Compiler"],
function(Tonyu, Tonyu_iterator, TonyuLang, ObjectMatcher, TError, IndentBuffer,
context, Visitor,cu) {
return cu.JSGenerator=(function () {
// TonyuソースファイルをJavascriptに変換する
var TH="_thread",THIZ="_this", ARGS="_arguments",FIBPRE="fiber$", FRMPC="__pc", LASTPOS="$LASTPOS",CNTV="__cnt",CNTC=100;//G
var BINDF="Tonyu.bindFunc";
var INVOKE_FUNC="Tonyu.invokeMethod";
var CALL_FUNC="Tonyu.callFunc";
var CHK_NN="Tonyu.checkNonNull";
var CLASS_HEAD="Tonyu.classes.", GLOBAL_HEAD="Tonyu.globals.";
var GET_THIS="this.isTonyuObject?this:Tonyu.not_a_tonyu_object(this)";
var ITER="Tonyu.iterator";
/*var ScopeTypes={FIELD:"field", METHOD:"method", NATIVE:"native",//B
LOCAL:"local", THVAR:"threadvar", PARAM:"param", GLOBAL:"global", CLASS:"class"};*/
var ScopeTypes=cu.ScopeTypes;
//var genSt=cu.newScopeType;
var stype=cu.getScopeType;
//var newScope=cu.newScope;
//var nc=cu.nullCheck;
//var genSym=cu.genSym;
var annotation3=cu.annotation;
var getMethod2=cu.getMethod;
var getDependingClasses=cu.getDependingClasses;
var getParams=cu.getParams;
//-----------
function genJS(klass, env) {//B
var srcFile=klass.src.tonyu; //file object //S
var srcCont=srcFile.text();
function getSource(node) {
return cu.getSource(srcCont,node);
}
var buf=IndentBuffer();
var printf=buf.printf;
var ctx=context();
var debug=false;
var OM=ObjectMatcher;
var traceTbl=env.traceTbl;
// method := fiber | function
var decls=klass.decls;
var fields=decls.fields,
methods=decls.methods,
natives=decls.natives;
// ↑ このクラスが持つフィールド,ファイバ,関数,ネイティブ変数の集まり.親クラスの宣言は含まない
var ST=ScopeTypes;
var fnSeq=0;
var diagnose=env.options.compiler.diagnose;
function annotation(node, aobj) {//B
return annotation3(klass.annotation,node,aobj);
}
function getMethod(name) {//B
return getMethod2(klass,name);
}
function getClassName(klass){// should be object or short name //G
if (typeof klass=="string") return CLASS_HEAD+(env.aliases[klass] || klass);//CFN CLASS_HEAD+env.aliases[klass](null check)
if (klass.builtin) return klass.fullName;// CFN klass.fullName
return CLASS_HEAD+klass.fullName;// CFN klass.fullName
}
function getClassNames(cs){//G
var res=[];
cs.forEach(function (c) { res.push(getClassName(c)); });
return res;
}
function enterV(obj, node) {//G
return function (buf) {
ctx.enter(obj,function () {
v.visit(node);
});
};
}
function varAccess(n, si, an) {//G
var t=stype(si);
if (t==ST.THVAR) {
buf.printf("%s",TH);
} else if (t==ST.FIELD) {
buf.printf("%s.%s",THIZ, n);
} else if (t==ST.METHOD) {
if (an && an.noBind) {
buf.printf("%s.%s",THIZ, n);
} else {
buf.printf("%s(%s,%s.%s)",BINDF, THIZ, THIZ, n);
}
} else if (t==ST.CLASS) {
buf.printf("%s",getClassName(n));
} else if (t==ST.GLOBAL) {
buf.printf("%s%s",GLOBAL_HEAD, n);
} else if (t==ST.PARAM || t==ST.LOCAL || t==ST.NATIVE) {
buf.printf("%s",n);
} else {
console.log("Unknown scope type: ",t);
throw new Error("Unknown scope type: "+t);
}
return si;
}
function noSurroundCompoundF(node) {//G
return function () {
noSurroundCompound.apply(this, [node]);
};
}
function noSurroundCompound(node) {//G
if (node.type=="compound") {
ctx.enter({noWait:true},function () {
buf.printf("%j%n", ["%n",node.stmts]);
// buf.printf("%{%j%n%}", ["%n",node.stmts]);
});
} else {
v.visit(node);
}
}
function lastPosF(node) {//G
return function () {
buf.printf("%s%s=%s;//%s%n", (env.options.compiler.commentLastPos?"//":""),
LASTPOS, traceTbl.add(klass/*.src.tonyu*/,node.pos ), klass.fullName+":"+node.pos);
};
}
var THNode={type:"THNode"};//G
v=buf.visitor=Visitor({//G
THNode: function (node) {
buf.printf(TH);
},
dummy: function (node) {
buf.printf("",node);
},
literal: function (node) {
buf.printf("%s",node.text);
},
paramDecl: function (node) {
buf.printf("%v",node.name);
},
paramDecls: function (node) {
buf.printf("(%j)",[", ",node.params]);
},
funcDeclHead: function (node) {
buf.printf("function %v %v",node.name, node.params);
},
funcDecl: function (node) {
},
"return": function (node) {
if (ctx.inTry) throw TError("現実装では、tryの中にreturnは書けません",srcFile,node.pos);
if (!ctx.noWait) {
if (node.value) {
buf.printf("%s.exit(%v);return;",TH,node.value);
} else {
buf.printf("%s.exit(%s);return;",TH,THIZ);
}
} else {
if (ctx.threadAvail) {
if (node.value) {
buf.printf("%s.retVal=%v;return;%n",TH, node.value);
} else {
buf.printf("%s.retVal=%s;return;%n",TH, THIZ);
}
} else {
if (node.value) {
buf.printf("return %v;",node.value);
} else {
buf.printf("return %s;",THIZ);
}
}
}
},
program: function (node) {
genClass(node.stmts);
},
number: function (node) {
buf.printf("%s", node.value );
},
reservedConst: function (node) {
if (node.text=="this") {
buf.printf("%s",THIZ);
} else if (node.text=="arguments" && ctx.threadAvail) {
buf.printf("%s",ARGS);
} else if (node.text==TH) {
buf.printf("%s", (ctx.threadAvail)?TH:"null");
} else {
buf.printf("%s", node.text);
}
},
varDecl: function (node) {
if (node.value) {
buf.printf("%v = %v", node.name, node.value );
} else {
buf.printf("%v", node.name);
}
},
varsDecl: function (node) {
lastPosF(node)();
buf.printf("%j;", [";",node.decls]);
},
jsonElem: function (node) {
if (node.value) {
buf.printf("%v: %v", node.key, node.value);
} else {
buf.printf("%v: %f", node.key, function () {
var si=varAccess( node.key.text, annotation(node).scopeInfo, annotation(node));
});
}
},
objlit: function (node) {
buf.printf("{%j}", [",", node.elems]);
},
arylit: function (node) {
buf.printf("[%j]", [",", node.elems]);
},
funcExpr: function (node) {
genFuncExpr(node);
},
parenExpr: function (node) {
buf.printf("(%v)",node.expr);
},
varAccess: function (node) {
var n=node.name.text;
var si=varAccess(n,annotation(node).scopeInfo, annotation(node));
},
exprstmt: function (node) {//exprStmt
var t={};
lastPosF(node)();
if (!ctx.noWait) {
t=annotation(node).fiberCall || {};
}
if (t.type=="noRet") {
buf.printf(
"%s.%s%s(%j);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{",
THIZ, FIBPRE, t.N, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++
);
} else if (t.type=="ret") {
buf.printf(
"%s.%s%s(%j);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{"+
"%v%v%s.retVal;%n",
THIZ, FIBPRE, t.N, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++,
t.L, t.O, TH
);
} else if (t.type=="noRetSuper") {
var p=getClassName(klass.superClass);
buf.printf(
"%s.prototype.%s%s.apply( %s, [%j]);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{",
p, FIBPRE, t.S.name.text, THIZ, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++
);
} else if (t.type=="retSuper") {
buf.printf(
"%s.prototype.%s%s.apply( %s, [%j]);%n" +
"%s=%s;return;%n" +/*B*/
"%}case %d:%{"+
"%v%v%s.retVal;%n",
p, FIBPRE, t.S.name.text, THIZ, [", ",[THNode].concat(t.A)],
FRMPC, ctx.pc,
ctx.pc++,
t.L, t.O, TH
);
} else {
buf.printf("%v;", node.expr );
}
},
infix: function (node) {
var opn=node.op.text;
/*if (opn=="=" || opn=="+=" || opn=="-=" || opn=="*=" || opn=="/=" || opn=="%=" ) {
checkLVal(node.left);
}*/
if (diagnose) {
if (opn=="+" || opn=="-" || opn=="*" || opn=="/" || opn=="%" ) {
buf.printf("%s(%v,%l)%v%s(%v,%l)", CHK_NN, node.left, getSource(node.left), node.op,
CHK_NN, node.right, getSource(node.right));
return;
}
if (opn=="+=" || opn=="-=" || opn=="*=" || opn=="/=" || opn=="%=" ) {
buf.printf("%v%v%s(%v,%l)", node.left, node.op,
CHK_NN, node.right, getSource(node.right));
return;
}
}
buf.printf("%v%v%v", node.left, node.op, node.right);
},
trifixr:function (node) {
buf.printf("%v%v%v%v%v", node.left, node.op1, node.mid, node.op2, node.right);
},
prefix: function (node) {
buf.printf("%v %v", node.op, node.right);
},
postfix: function (node) {
var a=annotation(node);
if (diagnose) {
if (a.myMethodCall) {
var mc=a.myMethodCall;
var si=mc.scopeInfo;
var st=stype(si);
if (st==ST.FIELD || st==ST.METHOD) {
buf.printf("%s(%s, %l, [%j], %l )", INVOKE_FUNC,THIZ, mc.name, [",",mc.args],"this");
} else {
buf.printf("%s(%v, [%j], %l)", CALL_FUNC, node.left, [",",mc.args], getSource(node.left));
}
return;
} else if (a.othersMethodCall) {
var oc=a.othersMethodCall;
buf.printf("%s(%v, %l, [%j], %l )", INVOKE_FUNC, oc.target, oc.name, [",",oc.args],getSource(oc.target));
return;
} else if (a.memberAccess) {
var ma=a.memberAccess;
buf.printf("%s(%v,%l).%s", CHK_NN, ma.target, getSource(ma.target), ma.name );
return;
}
} else if (a.myMethodCall) {
var mc=a.myMethodCall;
var si=mc.scopeInfo;
var st=stype(si);
if (st==ST.METHOD) {
buf.printf("%s.%s(%j)",THIZ, mc.name, [",",mc.args]);
return;
}
}
buf.printf("%v%v", node.left, node.op);
},
"break": function (node) {
if (!ctx.noWait) {
if (ctx.inTry && ctx.exitTryOnJump) throw TError("現実装では、tryの中にbreak;は書けません",srcFile,node.pos);
if (ctx.closestBrk) {
buf.printf("%s=%z; break;%n", FRMPC, ctx.closestBrk);
} else {
throw TError( "break; は繰り返しの中で使います" , srcFile, node.pos);
}
} else {
buf.printf("break;%n");
}
},
"try": function (node) {
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasJump || an.hasReturn)) {
//buf.printf("/*try catch in wait mode is not yet supported*/%n");
if (node.catches.length!=1 || node.catches[0].type!="catch") {
throw TError("現実装では、catch節1個のみをサポートしています",srcFile,node.pos);
}
var ct=node.catches[0];
var catchPos={},finPos={};
buf.printf("%s.enterTry(%z);%n",TH,catchPos);
buf.printf("%f", enterV({inTry:true, exitTryOnJump:true},node.stmt) );
buf.printf("%s.exitTry();%n",TH);
buf.printf("%s=%z;break;%n",FRMPC,finPos);
buf.printf("%}case %f:%{",function (){
buf.print(catchPos.put(ctx.pc++));
});
buf.printf("%s=%s.startCatch();%n",ct.name.text, TH);
buf.printf("%s.exitTry();%n",TH);
buf.printf("%v%n", ct.stmt);
buf.printf("%}case %f:%{",function (){
buf.print(finPos.put(ctx.pc++));
});
} else {
ctx.enter({noWait:true}, function () {
buf.printf("try {%{%f%n%}} ",
noSurroundCompoundF(node.stmt));
node.catches.forEach(v.visit);
});
}
},
"catch": function (node) {
buf.printf("catch (%s) {%{%f%n%}}",node.name.text, noSurroundCompoundF(node.stmt));
},
"throw": function (node) {
buf.printf("throw %v;%n",node.ex);
},
"while": function (node) {
lastPosF(node)();
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasReturn)) {
var brkpos=buf.lazy();
var pc=ctx.pc++;
var isTrue= node.cond.type=="reservedConst" && node.cond.text=="true";
buf.printf(
/*B*/
"%}case %d:%{" +
(isTrue?"%D%D%D":"if (!(%v)) { %s=%z; break; }%n") +
"%f%n" +
"%s=%s;break;%n" +
"%}case %f:%{",
pc,
node.cond, FRMPC, brkpos,
enterV({closestBrk:brkpos, exitTryOnJump:false}, node.loop),
FRMPC, pc,
function () { buf.print(brkpos.put(ctx.pc++)); }
);
} else {
ctx.enter({noWait:true},function () {
buf.printf("while (%v) {%{%f%n%}}", node.cond, noSurroundCompoundF(node.loop));
});
}
},
"for": function (node) {
lastPosF(node)();
var an=annotation(node);
if (node.inFor.type=="forin") {
var itn=annotation(node.inFor).iterName;
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasReturn)) {
var brkpos=buf.lazy();
var pc=ctx.pc++;
buf.printf(
"%s=%s(%v,%s);%n"+
"%}case %d:%{" +
"if (!(%s.next())) { %s=%z; break; }%n" +
"%f%n" +
"%f%n" +
"%s=%s;break;%n" +
"%}case %f:%{",
itn, ITER, node.inFor.set, node.inFor.vars.length,
pc,
itn, FRMPC, brkpos,
getElemF(itn, node.inFor.isVar, node.inFor.vars),
enterV({closestBrk:brkpos, exitTryOnJump:false}, node.loop),//node.loop,
FRMPC, pc,
function (buf) { buf.print(brkpos.put(ctx.pc++)); }
);
} else {
ctx.enter({noWait:true},function() {
buf.printf(
"%s=%s(%v,%s);%n"+
"while(%s.next()) {%{" +
"%f%n"+
"%f%n" +
"%}}",
itn, ITER, node.inFor.set, node.inFor.vars.length,
itn,
getElemF(itn, node.inFor.isVar, node.inFor.vars),
noSurroundCompoundF(node.loop)
);
});
}
} else {
if (!ctx.noWait&&
(an.fiberCallRequired || an.hasReturn)) {
var brkpos=buf.lazy();
var pc=ctx.pc++;
buf.printf(
"%v;%n"+
"%}case %d:%{" +
"if (!(%v)) { %s=%z; break; }%n" +
"%f%n" +
"%v;%n" +
"%s=%s;break;%n" +
"%}case %f:%{",
node.inFor.init ,
pc,
node.inFor.cond, FRMPC, brkpos,
enterV({closestBrk:brkpos,exitTryOnJump:false}, node.loop),//node.loop,
node.inFor.next,
FRMPC, pc,
function (buf) { buf.print(brkpos.put(ctx.pc++)); }
);
} else {
ctx.enter({noWait:true},function() {
buf.printf(
"%v%n"+
"while(%v) {%{" +
"%v%n" +
"%v;%n" +
"%}}",
node.inFor.init ,
node.inFor.cond,
node.loop,
node.inFor.next
);
});
}
}
function getElemF(itn, isVar, vars) {
return function () {
vars.forEach(function (v,i) {
buf.printf("%s=%s[%s];%n", v.text, itn, i);
});
};
}
},
"if": function (node) {
lastPosF(node)();
//buf.printf("/*FBR=%s*/",!!annotation(node).fiberCallRequired);
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasJump || an.hasReturn)) {
var fipos={}, elpos={};
if (node._else) {
buf.printf(
"if (!(%v)) { %s=%z; break; }%n" +
"%v%n" +
"%s=%z;break;%n" +
"%}case %f:%{" +
"%v%n" +
/*B*/
"%}case %f:%{" ,
node.cond, FRMPC, elpos,
node.then,
FRMPC, fipos,
function () { buf.print(elpos.put(ctx.pc++)); },
node._else,
function () { buf.print(fipos.put(ctx.pc++)); }
);
} else {
buf.printf(
"if (!(%v)) { %s=%z; break; }%n" +
"%v%n" +
/*B*/
"%}case %f:%{",
node.cond, FRMPC, fipos,
node.then,
function () { buf.print(fipos.put(ctx.pc++)); }
);
}
} else {
ctx.enter({noWait:true}, function () {
if (node._else) {
buf.printf("if (%v) {%{%f%n%}} else {%{%f%n%}}", node.cond,
noSurroundCompoundF(node.then),
noSurroundCompoundF(node._else));
} else {
buf.printf("if (%v) {%{%f%n%}}", node.cond,
noSurroundCompoundF(node.then));
}
});
}
},
ifWait: function (node) {
if (!ctx.noWait) {
buf.printf("%v",node.then);
} else {
if (node._else) {
buf.printf("%v",node._else);
}
}
},
call: function (node) {
buf.printf("(%j)", [",",node.args]);
},
objlitArg: function (node) {
buf.printf("%v",node.obj);
},
argList: function (node) {
buf.printf("%j",[",",node.args]);
},
newExpr: function (node) {
var p=node.params;
if (p) {
buf.printf("new %v%v",node.klass,p);
} else {
buf.printf("new %v",node.klass);
}
},
scall: function (node) {
buf.printf("[%j]", [",",node.args]);
},
superExpr: function (node) {
var name;
if (!klass.superClass) throw new Error(klass.fullName+"には親クラスがありません");
if (node.name) {
name=node.name.text;
buf.printf("%s.prototype.%s.apply( %s, %v)",
getClassName(klass.superClass), name, THIZ, node.params);
} else {
buf.printf("%s.apply( %s, %v)",
getClassName(klass.superClass), THIZ, node.params);
}
},
arrayElem: function (node) {
buf.printf("[%v]",node.subscript);
},
member: function (node) {
buf.printf(".%v",node.name);
},
symbol: function (node) {
buf.print(node.text);
},
"normalFor": function (node) {
buf.printf("%v; %v; %v", node.init, node.cond, node.next);
},
compound: function (node) {
var an=annotation(node);
if (!ctx.noWait &&
(an.fiberCallRequired || an.hasJump || an.hasReturn) ) {
buf.printf("%j", ["%n",node.stmts]);
} else {
/*if (ctx.noSurroundBrace) {
ctx.enter({noSurroundBrace:false,noWait:true},function () {
buf.printf("%{%j%n%}", ["%n",node.stmts]);
});
} else {*/
ctx.enter({noWait:true},function () {
buf.printf("{%{%j%n%}}", ["%n",node.stmts]);
});
//}
}
},
"typeof": function (node) {
buf.printf("typeof ");
},
"instanceof": function (node) {
buf.printf(" instanceof ");
},
"is": function (node) {
buf.printf(" instanceof ");
},
regex: function (node) {
buf.printf("%s",node.text);
}
});
var opTokens=["++", "--", "!==", "===", "+=", "-=", "*=", "/=",
"%=", ">=", "<=",
"!=", "==", ">>", "<<", "&&", "||", ">", "<", "+", "?", "=", "*",
"%", "/", "^", "~", "\\", ":", ";", ",", "!", "&", "|", "-"
,"delete" ];
opTokens.forEach(function (opt) {
v.funcs[opt]=function (node) {
buf.printf("%s",opt);
};
});
//v.debug=debug;
v.def=function (node) {
console.log("Err node=");
console.log(node);
throw node.type+" is not defined in visitor:compiler2";
};
v.cnt=0;
function genSource() {//G
//annotateSource();
/*if (env.options.compiler.asModule) {
klass.moduleName=getClassName(klass);
printf("if (typeof requireSimulator=='object') requireSimulator.setName(%l);%n",klass.moduleName);
printf("//requirejs(['Tonyu'%f],function (Tonyu) {%{", function (){
getDependingClasses(klass).forEach(function (k) {
printf(",%l",k.moduleName);
});
});
}*/
ctx.enter({/*scope:topLevelScope*/}, function () {
var nspObj=CLASS_HEAD+klass.namespace;
printf("Tonyu.klass.ensureNamespace(%s,%l);%n",CLASS_HEAD.replace(/\.$/,""), klass.namespace);
//printf(nspObj+"="+nspObj+"||{};%n");
if (klass.superClass) {
printf("%s=Tonyu.klass(%s,[%s],{%{",
getClassName(klass),
getClassName(klass.superClass),
getClassNames(klass.includes).join(","));
} else {
printf("%s=Tonyu.klass([%s],{%{",
getClassName(klass),
getClassNames(klass.includes).join(","));
}
for (var name in methods) {
if (debug) console.log("method1", name);
var method=methods[name];
//initParamsLocals(method);
//annotateMethodFiber(method);
ctx.enter({noWait:true, threadAvail:false}, function () {
genFunc(method);
});
if (debug) console.log("method2", name);
//v.debug=debug;
if (!method.nowait ) {
ctx.enter({noWait:false,threadAvail:true}, function () {
genFiber(method);
});
}
if (debug) console.log("method3", name);
}
printf("__dummy: false%n");
printf("%}});%n");
});
printf("Tonyu.klass.addMeta(%s,%s);%n",
getClassName(klass),JSON.stringify(digestMeta(klass)));
//if (env.options.compiler.asModule) {
// printf("//%}});");
//}
}
function digestMeta(klass) {//G
var res={
fullName: klass.fullName,
namespace: klass.namespace,
shortName: klass.shortName,
decls:{methods:{}}
};
for (var i in klass.decls.methods) {
res.decls.methods[i]=
{nowait:!!klass.decls.methods[i].nowait};
}
return res;
}
function genFiber(fiber) {//G
if (isConstructor(fiber)) return;
var stmts=fiber.stmts;
var noWaitStmts=[], waitStmts=[], curStmts=noWaitStmts;
var opt=true;
if (opt) {
stmts.forEach(function (s) {
if (annotation(s).fiberCallRequired) {
curStmts=waitStmts;
}
curStmts.push(s);
});
} else {
waitStmts=stmts;
}
printf(
"%s%s :function %s(%j) {%{"+
"var %s=%s;%n"+
"%svar %s=%s;%n"+
"var %s=0;%n"+
"%f%n"+
"%f%n",
FIBPRE, fiber.name, genFn(fiber.pos,"f_"+fiber.name), [",",[THNode].concat(fiber.params)],
THIZ, GET_THIS,
(fiber.useArgs?"":"//"), ARGS, "Tonyu.A(arguments)",
FRMPC,
genLocalsF(fiber),
nfbody
);
if (waitStmts.length>0) {
printf(
"%s.enter(function %s(%s) {%{"+
"if (%s.lastEx) %s=%s.catchPC;%n"+
"for(var %s=%d ; %s--;) {%{"+
"switch (%s) {%{"+
"%}case 0:%{"+
"%f" +
"%s.exit(%s);return;%n"+
"%}}%n"+
"%}}%n"+
"%}});%n",
TH,genFn(fiber.pos,"ent_"+fiber.name),TH,
TH,FRMPC,TH,
CNTV, CNTC, CNTV,
FRMPC,
// case 0:
fbody,
TH,THIZ
);
} else {
printf("%s.retVal=%s;return;%n",TH,THIZ);
}
printf("%}},%n");
function nfbody() {
ctx.enter({method:fiber, /*scope: fiber.scope,*/ noWait:true, threadAvail:true }, function () {
noWaitStmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
function fbody() {
ctx.enter({method:fiber, /*scope: fiber.scope,*/
finfo:fiber, pc:1}, function () {
waitStmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genFunc(func) {//G
var fname= isConstructor(func) ? "initialize" : func.name;
printf("%s :function %s(%j) {%{"+
"var %s=%s;%n"+
"%f%n" +
"%f" +
"%}},%n",
fname, genFn(func.pos,fname), [",",func.params],
THIZ, GET_THIS,
genLocalsF(func),
fbody
);
function fbody() {
ctx.enter({method:func, finfo:func,
/*scope: func.scope*/ }, function () {
func.stmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genFuncExpr(node) {//G
var finfo=annotation(node);// annotateSubFuncExpr(node);
buf.printf("function (%j) {%{"+
"%f%n"+
"%f"+
"%}}"
,
[",", finfo.params],
genLocalsF(finfo),
fbody
);
function fbody() {
ctx.enter({noWait: true, threadAvail:false,
finfo:finfo, /*scope: finfo.scope*/ }, function () {
node.body.stmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genFn(pos,name) {//G
if (!name) name=(fnSeq++)+"";
return ("_trc_"+klass.shortName+"_"+name)
// return ("_trc_func_"+traceTbl.add(klass,pos )+"_"+(fnSeq++));// Math.random()).replace(/\./g,"");
}
function genSubFunc(node) {//G
var finfo=annotation(node);// annotateSubFuncExpr(node);
buf.printf("function %s(%j) {%{"+
"%f%n"+
"%f"+
"%}}"
,
finfo.name,[",", finfo.params],
genLocalsF(finfo),
fbody
);
function fbody() {
ctx.enter({noWait: true, threadAvail:false,
finfo:finfo, /*scope: finfo.scope*/ }, function () {
node.body.stmts.forEach(function (stmt) {
printf("%v%n", stmt);
});
});
}
}
function genLocalsF(finfo) {//G
return f;
function f() {
ctx.enter({/*scope:finfo.scope*/}, function (){
for (var i in finfo.locals.varDecls) {
buf.printf("var %s;%n",i);
}
for (var i in finfo.locals.subFuncDecls) {
genSubFunc(finfo.locals.subFuncDecls[i]);
}
});
};
}
function isConstructor(f) {//G
return OM.match(f, {ftype:"constructor"}) || OM.match(f, {name:"new"});
}
genSource();//G
klass.src.js=buf.buf;//G
if (debug) {
console.log("method4", buf.buf);
//throw "ERR";
}
return buf.buf;
}//B
return {genJS:genJS};
})();
//if (typeof getReq=="function") getReq.exports("Tonyu.Compiler");
});
|
superClass->superclass (2)
|
js/lang/JSGenerator.js
|
superClass->superclass (2)
|
<ide><path>s/lang/JSGenerator.js
<ide> t.L, t.O, TH
<ide> );
<ide> } else if (t.type=="noRetSuper") {
<del> var p=getClassName(klass.superClass);
<add> var p=getClassName(klass.superclass);
<ide> buf.printf(
<ide> "%s.prototype.%s%s.apply( %s, [%j]);%n" +
<ide> "%s=%s;return;%n" +/*B*/
<ide> },
<ide> superExpr: function (node) {
<ide> var name;
<del> if (!klass.superClass) throw new Error(klass.fullName+"には親クラスがありません");
<add> if (!klass.superclass) throw new Error(klass.fullName+"には親クラスがありません");
<ide> if (node.name) {
<ide> name=node.name.text;
<ide> buf.printf("%s.prototype.%s.apply( %s, %v)",
<del> getClassName(klass.superClass), name, THIZ, node.params);
<add> getClassName(klass.superclass), name, THIZ, node.params);
<ide> } else {
<ide> buf.printf("%s.apply( %s, %v)",
<del> getClassName(klass.superClass), THIZ, node.params);
<add> getClassName(klass.superclass), THIZ, node.params);
<ide> }
<ide> },
<ide> arrayElem: function (node) {
<ide> };
<ide> v.cnt=0;
<ide> function genSource() {//G
<del> //annotateSource();
<ide> /*if (env.options.compiler.asModule) {
<ide> klass.moduleName=getClassName(klass);
<ide> printf("if (typeof requireSimulator=='object') requireSimulator.setName(%l);%n",klass.moduleName);
<ide> });
<ide> });
<ide> }*/
<del> ctx.enter({/*scope:topLevelScope*/}, function () {
<add> ctx.enter({}, function () {
<ide> var nspObj=CLASS_HEAD+klass.namespace;
<ide> printf("Tonyu.klass.ensureNamespace(%s,%l);%n",CLASS_HEAD.replace(/\.$/,""), klass.namespace);
<del> //printf(nspObj+"="+nspObj+"||{};%n");
<del> if (klass.superClass) {
<add> if (klass.superclass) {
<ide> printf("%s=Tonyu.klass(%s,[%s],{%{",
<ide> getClassName(klass),
<del> getClassName(klass.superClass),
<add> getClassName(klass.superclass),
<ide> getClassNames(klass.includes).join(","));
<ide> } else {
<ide> printf("%s=Tonyu.klass([%s],{%{",
<ide> getClassName(klass),
<ide> getClassNames(klass.includes).join(","));
<ide> }
<add> //printf("Tonyu.klass.define({%{");
<add> //printf("fullName:")
<ide> for (var name in methods) {
<ide> if (debug) console.log("method1", name);
<ide> var method=methods[name];
<del> //initParamsLocals(method);
<del> //annotateMethodFiber(method);
<ide> ctx.enter({noWait:true, threadAvail:false}, function () {
<ide> genFunc(method);
<ide> });
<ide> if (debug) console.log("method2", name);
<del> //v.debug=debug;
<ide> if (!method.nowait ) {
<ide> ctx.enter({noWait:false,threadAvail:true}, function () {
<ide> genFiber(method);
|
|
Java
|
apache-2.0
|
6a1784ab588ec0bf8cd84bea56f5ebd0be1f5646
| 0 |
lostiniceland/org.ops4j.pax.web,lostiniceland/org.ops4j.pax.web
|
package org.ops4j.pax.web.service;
import java.util.EventListener;
import javax.servlet.Filter;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
/**
* xtended Http Service allows bundles to dynamically:<br/>
* * register and unregister event listeners, for better control over the life cycle of ServletContext, HttpSession and
* ServletRequest;<br/>
* * register and unregister filters into the URI namespace of Http Service
*
* @author Alin Dreghiciu
* @since 0.5.2
*/
public interface ExtendedHttpService
extends HttpService
{
/**
* Registers an event listener.
* Depending on the listener type, the listener will be notified on different life cycle events. The following
* listeners are supported:<br/>
* HttpSessionActivationListener, HttpSessionAttributeListener, HttpSessionBindingListener, HttpSessionListener,
* ServletContextListener, ServletContextAttributeListener, ServletRequestListener, ServletRequestAttributeListener.
* Check out Servlet specification for details on what type of event the registered listener will be notified.
*
* @param listener an event listener to be registered. If null an IllegalArgumentException is thrown.
* @param httpContext the http context this listener is for. If null a default http context will be used.
*/
void registerEventListener( EventListener listener, HttpContext httpContext );
/**
* Unregisters a previously registered listener.
*
* @param listener the event listener to be unregistered.
*
* @throws IllegalArgumentException if the listener is unknown to the http service (never registered or unregistered
* before) or the listener is null
*/
void unregisterEventListener( EventListener listener );
/**
* Registers a servlet flter.
*
* @param filter a servlet filter. If null an IllegalArgumentException is thrown.
* @param urlPatterns url patterns this filter maps to
* @param aliases servlet / resource aliases this filter maps to
* @param httpContext the http context this filter is for. If null a default http context will be used.
*/
void registerFilter( Filter filter, String[] urlPatterns, String[] aliases, HttpContext httpContext );
/**
* Unregisters a previously registeredservlet filter.
*
* @param filter the servlet filter to be unregistered
*
* @throws IllegalArgumentException if the filter is unknown to the http service (never registered or unregistered
* before) or the filter is null
*/
void unregisterFilter( Filter filter );
}
|
service/src/main/java/org/ops4j/pax/web/service/ExtendedHttpService.java
|
package org.ops4j.pax.web.service;
import java.util.EventListener;
import javax.servlet.Filter;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
/**
* xtended Http Service allows bundles to dynamically:<br/>
* * register and unregister event listeners, for better control over the life cycle of ServletContext, HttpSession and
* ServletRequest;<br/>
* * register and unregister filters into the URI namespace of Http Service
*
* @author Alin Dreghiciu
* @since 0.5.2
*/
public interface ExtendedHttpService
extends HttpService
{
/**
* Registers an event listener.
* Depending on the listener type, the listener will be notified on different life cycle events. The following
* listeners are supported:<br/>
* HttpSessionActivationListener, HttpSessionAttributeListener, HttpSessionBindingListener, HttpSessionListener,
* ServletContextListener, ServletContextAttributeListener, ServletRequestListener, ServletRequestAttributeListener.
* Check out Servlet specification for details on what type of event the registered listener will be notified.
*
* @param listener an event listener to be registered. If null an IllegalArgumentException is thrown.
* @param httpContext the http context this listener is for. If null a default http context will be used.
*/
void registerEventListener( EventListener listener, HttpContext httpContext );
/**
* Unregisters a previously registered listener.
*
* @param listener the event listener to be unregistered.
*
* @throws IllegalArgumentException if the listener is unknown to the http service (never registered or unregistered
* before) or the listener is null
*/
void unregisterEventListener( EventListener listener );
/**
* Registers a servlet flter.
*
* @param filter a servlet filter. If null an IllegalArgumentException is thrown.
* @param urlPatterns url patterns this filter maps to
* @param aliases servlet / resource aliases this filter maps to
* @param httpContext the http context this filter is for. If null a default http context will be used.
*/
void registerFilter( Filter filter, String[] urlPatterns, String[] aliases, HttpContext httpContext );
/**
* Unregisters a previously servlet filter.
*
* @param filter the servlet filter to be unregistered.
* @throws IllegalArgumentException if the filter is unknown to the http service (never registered or unregistered
* before) or the filter is null
*/
void unregisterFilter( Filter filter );
}
|
JavaDoc improvements.
|
service/src/main/java/org/ops4j/pax/web/service/ExtendedHttpService.java
|
JavaDoc improvements.
|
<ide><path>ervice/src/main/java/org/ops4j/pax/web/service/ExtendedHttpService.java
<ide> void registerFilter( Filter filter, String[] urlPatterns, String[] aliases, HttpContext httpContext );
<ide>
<ide> /**
<del> * Unregisters a previously servlet filter.
<add> * Unregisters a previously registeredservlet filter.
<ide> *
<del> * @param filter the servlet filter to be unregistered.
<add> * @param filter the servlet filter to be unregistered
<add> *
<ide> * @throws IllegalArgumentException if the filter is unknown to the http service (never registered or unregistered
<ide> * before) or the filter is null
<ide> */
|
|
JavaScript
|
isc
|
9745634bc39cf03882b21db69a2d08209b934ed4
| 0 |
ryejs/rye,ryejs/rye
|
Rye.define('Query', function(){
var util = Rye.require('Util')
, _slice = Array.prototype.slice
, selectorRE = /^([.#]?)([\w\-]+)$/
, selectorType = {
'.': 'getElementsByClassName'
, '#': 'getElementById'
, '' : 'getElementsByTagName'
, '_': 'querySelectorAll'
}
, matchesSelector
function matches(element, selector) {
var match
if (!element || !util.isElement(element) || !selector) {
return false
}
if (selector.nodeType) {
return element === selector
}
if (selector instanceof Rye) {
return selector.elements.some(function(selector){
return matches(element, selector)
})
}
if (element === document) {
return false
}
matchesSelector = matchesSelector || (matchesSelector = element.matches || util.prefix('matchesSelector', element))
if (matchesSelector) {
return matchesSelector.call(element, selector)
}
// fall back to performing a selector:
if (!element.parentNode) {
dummyDiv.appendChild(element)
}
match = qsa(element.parentNode, selector).indexOf(element) >= 0
if (element.parentNode === dummyDiv) {
dummyDiv.removeChild(element)
}
return match
}
function qsa (element, selector) {
var method
element = element || document
// http://jsperf.com/getelementbyid-vs-queryselector/11
if (!selector.match(selectorRE) || (RegExp.$1 === '#' && element !== document)) {
method = selectorType._
} else {
method = selectorType[RegExp.$1]
selector = RegExp.$2
}
var result = element[method](selector)
if (util.isNodeList(result)){
return _slice.call(result)
}
if (util.isElement(result)){
return [result]
}
return []
}
// Walks the DOM tree using `method`, returns
// when an element node is found
function getClosestNode (element, method, selector) {
do {
element = element[method]
} while (element && ((selector && !matches(element, selector)) || !util.isElement(element)))
return element
}
// Creates a new Rye instance applying a filter if necessary
function _create (elements, selector) {
return selector == null ? new Rye(elements) : new Rye(elements).filter(selector)
}
this.qsa = qsa
this.find = function (selector) {
var elements
if (this.length === 1) {
elements = qsa(this.elements[0], selector)
} else {
elements = this.elements.reduce(function(elements, element){
return elements.concat(qsa(element, selector))
}, [])
}
return _create(elements)
}
this.filter = function (selector, inverse) {
if (typeof selector === 'function') {
var fn = selector
return _create(this.elements.filter(function(element, index){
return fn.call(element, element, index) != (inverse || false)
}))
}
if (selector && selector[0] === '!') {
selector = selector.substr(1)
inverse = true
}
return _create(this.elements.filter(function(element){
return matches(element, selector) != (inverse || false)
}))
}
this.contains = function (selector) {
var matches
return _create(this.elements.reduce(function(elements, element){
matches = qsa(element, selector)
return elements.concat(matches.length ? element : null)
}, []))
}
this.is = function (selector) {
return this.length > 0 && this.filter(selector).length > 0
}
this.not = function (selector) {
return this.filter(selector, true)
}
this.index = function (selector) {
if (selector == null) {
return this.parent().children().indexOf(this.elements[0])
}
return this.indexOf(new Rye(selector).elements[0])
}
this.add = function (selector, context) {
var elements = selector
if (typeof selector === 'string') {
elements = new Rye(selector, context).elements
}
return this.concat(elements)
}
// Extract a list with the provided property for each value.
// This works like underscore's pluck, with the added
// getClosestNode() method to avoid picking up non-html nodes.
this.pluckNode = function (property) {
return this.map(function(element){
return getClosestNode(element, property)
})
}
this.next = function () {
return _create(this.pluckNode('nextSibling'))
}
this.prev = function () {
return _create(this.pluckNode('previousSibling'))
}
this.first = function () {
return _create(this.get(0))
}
this.last = function () {
return _create(this.get(-1))
}
this.siblings = function (selector) {
var siblings = []
this.each(function(element){
_slice.call(element.parentNode.childNodes).forEach(function(child){
if (util.isElement(child) && child !== element){
siblings.push(child)
}
})
})
return _create(siblings, selector)
}
this.parent = function (selector) {
return _create(this.pluck('parentNode'), selector)
}
// borrow from zepto
this.parents = function (selector) {
var ancestors = []
, elements = this.elements
, fn = function (element) {
if ((element = element.parentNode) && element !== document && ancestors.indexOf(element) < 0) {
ancestors.push(element)
return element
}
}
while (elements.length > 0 && elements[0] !== undefined) {
elements = elements.map(fn)
}
return _create(ancestors, selector)
}
this.closest = function (selector) {
return this.map(function(element){
if (matches(element, selector)) {
return element
}
return getClosestNode(element, 'parentNode', selector)
})
}
this.children = function (selector) {
return _create(this.elements.reduce(function(elements, element){
var childrens = _slice.call(element.children)
return elements.concat(childrens)
}, []), selector)
}
return {
matches : matches
, qsa : qsa
, getClosestNode : getClosestNode
}
})
|
lib/query.js
|
Rye.define('Query', function(){
var util = Rye.require('Util')
, _slice = Array.prototype.slice
, selectorRE = /^([.#]?)([\w\-]+)$/
, selectorType = {
'.': 'getElementsByClassName'
, '#': 'getElementById'
, '' : 'getElementsByTagName'
, '_': 'querySelectorAll'
}
, dummyDiv = document.createElement('div')
, matchesSelector
function matches(element, selector) {
var match
if (!element || !util.isElement(element) || !selector) {
return false
}
if (selector.nodeType) {
return element === selector
}
if (selector instanceof Rye) {
return selector.elements.some(function(selector){
return matches(element, selector)
})
}
if (element === document) {
return false
}
matchesSelector = matchesSelector || (matchesSelector = element.matches || util.prefix('matchesSelector', dummyDiv))
if (matchesSelector) {
return matchesSelector.call(element, selector)
}
// fall back to performing a selector:
if (!element.parentNode) {
dummyDiv.appendChild(element)
}
match = qsa(element.parentNode, selector).indexOf(element) >= 0
if (element.parentNode === dummyDiv) {
dummyDiv.removeChild(element)
}
return match
}
function qsa (element, selector) {
var method
element = element || document
// http://jsperf.com/getelementbyid-vs-queryselector/11
if (!selector.match(selectorRE) || (RegExp.$1 === '#' && element !== document)) {
method = selectorType._
} else {
method = selectorType[RegExp.$1]
selector = RegExp.$2
}
var result = element[method](selector)
if (util.isNodeList(result)){
return _slice.call(result)
}
if (util.isElement(result)){
return [result]
}
return []
}
// Walks the DOM tree using `method`, returns
// when an element node is found
function getClosestNode (element, method, selector) {
do {
element = element[method]
} while (element && ((selector && !matches(element, selector)) || !util.isElement(element)))
return element
}
// Creates a new Rye instance applying a filter if necessary
function _create (elements, selector) {
return selector == null ? new Rye(elements) : new Rye(elements).filter(selector)
}
this.qsa = qsa
this.find = function (selector) {
var elements
if (this.length === 1) {
elements = qsa(this.elements[0], selector)
} else {
elements = this.elements.reduce(function(elements, element){
return elements.concat(qsa(element, selector))
}, [])
}
return _create(elements)
}
this.filter = function (selector, inverse) {
if (typeof selector === 'function') {
var fn = selector
return _create(this.elements.filter(function(element, index){
return fn.call(element, element, index) != (inverse || false)
}))
}
if (selector && selector[0] === '!') {
selector = selector.substr(1)
inverse = true
}
return _create(this.elements.filter(function(element){
return matches(element, selector) != (inverse || false)
}))
}
this.contains = function (selector) {
var matches
return _create(this.elements.reduce(function(elements, element){
matches = qsa(element, selector)
return elements.concat(matches.length ? element : null)
}, []))
}
this.is = function (selector) {
return this.length > 0 && this.filter(selector).length > 0
}
this.not = function (selector) {
return this.filter(selector, true)
}
this.index = function (selector) {
if (selector == null) {
return this.parent().children().indexOf(this.elements[0])
}
return this.indexOf(new Rye(selector).elements[0])
}
this.add = function (selector, context) {
var elements = selector
if (typeof selector === 'string') {
elements = new Rye(selector, context).elements
}
return this.concat(elements)
}
// Extract a list with the provided property for each value.
// This works like underscore's pluck, with the added
// getClosestNode() method to avoid picking up non-html nodes.
this.pluckNode = function (property) {
return this.map(function(element){
return getClosestNode(element, property)
})
}
this.next = function () {
return _create(this.pluckNode('nextSibling'))
}
this.prev = function () {
return _create(this.pluckNode('previousSibling'))
}
this.first = function () {
return _create(this.get(0))
}
this.last = function () {
return _create(this.get(-1))
}
this.siblings = function (selector) {
var siblings = []
this.each(function(element){
_slice.call(element.parentNode.childNodes).forEach(function(child){
if (util.isElement(child) && child !== element){
siblings.push(child)
}
})
})
return _create(siblings, selector)
}
this.parent = function (selector) {
return _create(this.pluck('parentNode'), selector)
}
// borrow from zepto
this.parents = function (selector) {
var ancestors = []
, elements = this.elements
, fn = function (element) {
if ((element = element.parentNode) && element !== document && ancestors.indexOf(element) < 0) {
ancestors.push(element)
return element
}
}
while (elements.length > 0 && elements[0] !== undefined) {
elements = elements.map(fn)
}
return _create(ancestors, selector)
}
this.closest = function (selector) {
return this.map(function(element){
if (matches(element, selector)) {
return element
}
return getClosestNode(element, 'parentNode', selector)
})
}
this.children = function (selector) {
return _create(this.elements.reduce(function(elements, element){
var childrens = _slice.call(element.children)
return elements.concat(childrens)
}, []), selector)
}
return {
matches : matches
, qsa : qsa
, getClosestNode : getClosestNode
}
})
|
Removed dummyDiv
You already have an element to retrieve matchesSelector from
|
lib/query.js
|
Removed dummyDiv
|
<ide><path>ib/query.js
<ide> , '' : 'getElementsByTagName'
<ide> , '_': 'querySelectorAll'
<ide> }
<del> , dummyDiv = document.createElement('div')
<ide> , matchesSelector
<ide>
<ide> function matches(element, selector) {
<ide> return false
<ide> }
<ide>
<del> matchesSelector = matchesSelector || (matchesSelector = element.matches || util.prefix('matchesSelector', dummyDiv))
<add> matchesSelector = matchesSelector || (matchesSelector = element.matches || util.prefix('matchesSelector', element))
<ide> if (matchesSelector) {
<ide> return matchesSelector.call(element, selector)
<ide> }
|
|
Java
|
mit
|
557ba8e5822cc8590c3ef7c8c35d58ed0dce88d9
| 0 |
etdev/algorithms,etdev/algorithms,etdev/algorithms,etdev/algorithms
|
import java.util.*;
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
Stack visited = new Stack();
public List<Integer> postorderTraversal(TreeNode root) {
TreeNode node;
visited.push(root);
while (visited.size > 0) {
node = visited.pop();
if (node.left != null) {
visited.push(node.left);
}
else if (node.right != null) {
visited.push(node.right);
}
else { list.add(node.val); }
}
return list;
}
public TreeNode getDeepLeft(TreeNode currentNode) {
while (currentNode.left != null) {
currentNode = currentNode.left;
}
return currentNode;
}
public class Stack {
ArrayList<TreeNode> list;
public int size = 0;
public Stack() {
list = new ArrayList<TreeNode>();
}
public TreeNode pop() {
TreeNode retVal = list.get(list.size()-1);
list.remove(list.remove(list.size()-1));
size--;
return retVal;
}
public void push(TreeNode val) {
list.add(val);
size++;
}
public String toString() {
return list.toString();
}
}
}
|
algorithms/10_binary_tree_postorder/Solution.java
|
import java.util.*;
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
Stack visited = new Stack();
public List<Integer> postorderTraversal(TreeNode root) {
TreeNode node;
visited.push(root);
while (visited.size > 0) {
node = visited.pop();
if (node.left != null) {
visited.push(node.left);
}
else if (node.right != null) {
visited.push(node.right);
}
else { list.add(node.val); }
}
return list;
}
public TreeNode getDeepLeft(TreeNode currentNode) {
while (currentNode.left != null) {
currentNode = currentNode.left;
}
return currentNode;
}
}
|
Put stack class inside Solution
|
algorithms/10_binary_tree_postorder/Solution.java
|
Put stack class inside Solution
|
<ide><path>lgorithms/10_binary_tree_postorder/Solution.java
<ide> }
<ide> return currentNode;
<ide> }
<add>
<add> public class Stack {
<add> ArrayList<TreeNode> list;
<add> public int size = 0;
<add>
<add> public Stack() {
<add> list = new ArrayList<TreeNode>();
<add> }
<add>
<add> public TreeNode pop() {
<add> TreeNode retVal = list.get(list.size()-1);
<add> list.remove(list.remove(list.size()-1));
<add> size--;
<add> return retVal;
<add> }
<add>
<add> public void push(TreeNode val) {
<add> list.add(val);
<add> size++;
<add> }
<add>
<add> public String toString() {
<add> return list.toString();
<add> }
<add> }
<ide> }
|
|
JavaScript
|
mit
|
6ec26e5bd256e7cb604cdb1eb7a09941f84ca652
| 0 |
hcrlab/access_teleop,hcrlab/access_teleop,hcrlab/access_teleop,hcrlab/access_teleop,hcrlab/access_teleop,hcrlab/access_teleop
|
/**
* Created by timadamson on 8/22/17.
*/
/**
* An App self adds 3 camera streams, and the controlers to move the robot
*/
App = function () {
// Set self to be this so that you can add variables to this inside a callback
var self = this;
// Set up ros
this.ros = new ROSLIB.Ros({
url : 'ws://localhost:9090'
});
this.ros.on('error', function(error) {
console.log('Error connecting to websocket server.');
});
self.arm = new Arm(this.ros);
//self.head = new Head(ros);
//self.gripper = new Gripper(ros);
// Adds 3 canvas image streams
// --------------------------------------------------------------------------------
// Dynamic Canvas Sizes
var elmntmjpegRightForearm = document.getElementById("camera1");
var rightForearmWidth=elmntmjpegRightForearm.clientWidth;
var rightForearmHeight=elmntmjpegRightForearm.clientHeight;
var elmntmjpegHead = document.getElementById("camera2");
var headWidth=elmntmjpegHead.clientWidth;
var headHeight=elmntmjpegHead.clientHeight;
var camera2Height = "480";
var camera2Width = "640";
var elmntmjpegLeftForearm = document.getElementById("mjpegLeftForearm");
var leftForearmWidth=elmntmjpegLeftForearm.clientWidth;
var leftForearmHeight=elmntmjpegLeftForearm.clientHeight;
// Create the right forearm viewer.
var forearmRViewer = new MJPEGCANVAS.Viewer({
divID : 'camera1',
host : 'localhost',
width : rightForearmWidth,
height : rightForearmHeight,
topic : '/rviz1/camera1/image'
});
// Create the head viewer.
var headViewer = new MJPEGCANVAS.Viewer({
divID : 'camera2',
host : 'localhost',
width : headWidth,
height : headHeight,
topic : '/rviz1/camera2/image'
});
// Create the left forearm viewer.
var forearmLViewer = new MJPEGCANVAS.Viewer({
divID : 'mjpegLeftForearm',
host : 'localhost',
width : leftForearmWidth,
height : leftForearmWidth,
topic : '/head_camera/rgb/image_raw'
});
// ------------------------------------------------------------------------------------------
init_flag = false;
};
|
frontend/app.js
|
/**
* Created by timadamson on 8/22/17.
*/
/**
* An App self adds 3 camera streams, and the controlers to move the robot
*/
App = function () {
// Set self to be this so that you can add variables to this inside a callback
var self = this;
// Set up ros
this.ros = new ROSLIB.Ros({
url : 'ws://localhost:9090'
});
this.ros.on('error', function(error) {
console.log('Error connecting to websocket server.');
});
self.arm = new Arm(this.ros);
//self.head = new Head(ros);
//self.gripper = new Gripper(ros);
// Adds 3 canvas image streams
// --------------------------------------------------------------------------------
var cameraHeight = "480";
var cameraWidth = "640";
// Dynamic Canvas Sizes
var elmntmjpegRightForearm = document.getElementById("camera1");
var rightForearmWidth=cameraWidth;
var rightForearmHeight=cameraHeight;
var elmntmjpegHead = document.getElementById("camera2");
var headWidth=cameraWidth;
var headHeight=cameraHeight;
var elmntmjpegLeftForearm = document.getElementById("mjpegLeftForearm");
var leftForearmWidth=elmntmjpegLeftForearm.clientWidth;
var leftForearmHeight=elmntmjpegLeftForearm.clientHeight;
var paper1 = Snap( "#svg1" ); //use element created above
var x = document.createElement("CANVAS");
var ctx = x.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 100);
// Create the right forearm viewer.
var forearmRViewer = new MJPEGCANVAS.Viewer({
divID : 'camera1',
host : 'localhost',
width : rightForearmWidth,
height : rightForearmHeight,
// topic : '/r_forearm_cam/image_raw',
topic : '/rviz1/camera1/image',
overlay: x
});
// Create the head viewer.
var headViewer = new MJPEGCANVAS.Viewer({
divID : 'camera2',
host : 'localhost',
width : headWidth,
height : headHeight,
topic : '/wide_stereo/left/image_raw'
// topic : '/rviz1/camera2/image'
});
// Create the left forearm viewer.
var forearmLViewer = new MJPEGCANVAS.Viewer({
divID : 'mjpegLeftForearm',
host : 'localhost',
width : leftForearmWidth,
height : leftForearmWidth,
topic : '/l_forearm_cam/image_raw'
// topic : '/head_camera/rgb/image_raw'
});
// ------------------------------------------------------------------------------------------
init_flag = false;
};
|
reverted changes from app
|
frontend/app.js
|
reverted changes from app
|
<ide><path>rontend/app.js
<ide> // Adds 3 canvas image streams
<ide> // --------------------------------------------------------------------------------
<ide>
<del> var cameraHeight = "480";
<del> var cameraWidth = "640";
<ide> // Dynamic Canvas Sizes
<ide> var elmntmjpegRightForearm = document.getElementById("camera1");
<del> var rightForearmWidth=cameraWidth;
<del> var rightForearmHeight=cameraHeight;
<add> var rightForearmWidth=elmntmjpegRightForearm.clientWidth;
<add> var rightForearmHeight=elmntmjpegRightForearm.clientHeight;
<ide>
<ide>
<ide> var elmntmjpegHead = document.getElementById("camera2");
<del> var headWidth=cameraWidth;
<del> var headHeight=cameraHeight;
<add> var headWidth=elmntmjpegHead.clientWidth;
<add> var headHeight=elmntmjpegHead.clientHeight;
<add> var camera2Height = "480";
<add> var camera2Width = "640";
<ide>
<ide> var elmntmjpegLeftForearm = document.getElementById("mjpegLeftForearm");
<ide> var leftForearmWidth=elmntmjpegLeftForearm.clientWidth;
<ide> var leftForearmHeight=elmntmjpegLeftForearm.clientHeight;
<del>
<del> var paper1 = Snap( "#svg1" ); //use element created above
<del>
<del>
<del> var x = document.createElement("CANVAS");
<del> var ctx = x.getContext("2d");
<del> ctx.fillStyle = "#FF0000";
<del> ctx.fillRect(0, 0, 150, 100);
<ide>
<ide> // Create the right forearm viewer.
<ide> var forearmRViewer = new MJPEGCANVAS.Viewer({
<ide> host : 'localhost',
<ide> width : rightForearmWidth,
<ide> height : rightForearmHeight,
<del>// topic : '/r_forearm_cam/image_raw',
<del> topic : '/rviz1/camera1/image',
<del> overlay: x
<add> topic : '/rviz1/camera1/image'
<ide> });
<ide>
<ide> // Create the head viewer.
<ide> host : 'localhost',
<ide> width : headWidth,
<ide> height : headHeight,
<del> topic : '/wide_stereo/left/image_raw'
<del>// topic : '/rviz1/camera2/image'
<add> topic : '/rviz1/camera2/image'
<ide> });
<ide>
<ide> // Create the left forearm viewer.
<ide> host : 'localhost',
<ide> width : leftForearmWidth,
<ide> height : leftForearmWidth,
<del> topic : '/l_forearm_cam/image_raw'
<del>// topic : '/head_camera/rgb/image_raw'
<add> topic : '/head_camera/rgb/image_raw'
<ide> });
<ide>
<ide> // ------------------------------------------------------------------------------------------
|
|
Java
|
apache-2.0
|
89c34392c2ccfe4b3d70b6def9068b7dcd6a5a94
| 0 |
igniterealtime/Openfire,GregDThomas/Openfire,speedy01/Openfire,magnetsystems/message-openfire,speedy01/Openfire,akrherz/Openfire,guusdk/Openfire,magnetsystems/message-openfire,igniterealtime/Openfire,speedy01/Openfire,akrherz/Openfire,akrherz/Openfire,guusdk/Openfire,GregDThomas/Openfire,speedy01/Openfire,guusdk/Openfire,guusdk/Openfire,Gugli/Openfire,Gugli/Openfire,Gugli/Openfire,magnetsystems/message-openfire,Gugli/Openfire,guusdk/Openfire,igniterealtime/Openfire,magnetsystems/message-openfire,GregDThomas/Openfire,Gugli/Openfire,GregDThomas/Openfire,speedy01/Openfire,igniterealtime/Openfire,GregDThomas/Openfire,akrherz/Openfire,akrherz/Openfire,magnetsystems/message-openfire,igniterealtime/Openfire
|
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.muc.spi;
import org.jivesoftware.messenger.container.*;
import org.jivesoftware.messenger.disco.DiscoInfoProvider;
import org.jivesoftware.messenger.disco.DiscoItemsProvider;
import org.jivesoftware.messenger.disco.DiscoServerItem;
import org.jivesoftware.messenger.disco.ServerItemsProvider;
import org.jivesoftware.messenger.forms.DataForm;
import org.jivesoftware.messenger.forms.FormField;
import org.jivesoftware.messenger.forms.XDataForm;
import org.jivesoftware.messenger.forms.spi.XDataFormImpl;
import org.jivesoftware.messenger.forms.spi.XFormFieldImpl;
import org.jivesoftware.messenger.muc.*;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.handler.IQRegisterHandler;
import org.jivesoftware.messenger.user.UserNotFoundException;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* Implements the chat server as a cached memory resident chat server. The server is also
* responsible for responding Multi-User Chat disco requests as well as removing inactive users from
* the rooms after a period of time and to maintain a log of the conversation in the rooms that
* require to log their conversations. The conversations log is saved to the database using a
* separate process<p>
*
* Rooms in memory are held in the instance variable rooms. For optimization reasons, persistent
* rooms that don't have occupants aren't kept in memory. But a client may need to discover all the
* rooms (present in memory or not). So MultiUserChatServerImpl uses a cache of persistent room
* surrogates. A room surrogate (lighter object) is created for each persistent room that is public,
* persistent but is not in memory. The cache starts up empty until a client requests the list of
* rooms through service discovery. Once the disco request is received the cache is filled up with
* persistent room surrogates. The cache will keep all the surrogates in memory for an hour. If the
* cache's entries weren't used in an hour, they will be removed from memory. Whenever a persistent
* room is removed from memory (because all the occupants have left), the cache is cleared. But if
* a persistent room is loaded from the database then the entry for that room in the cache is
* removed. Note: Since the cache contains an entry for each room surrogate and the clearing
* algorithm is based on the usage of each entry, it's possible that some entries are removed
* while others don't thus generating that the provided list of discovered rooms won't be complete.
* However, this possibility is low since the clients will most of the time ask for all the cache
* entries and then ask for a particular entry. Anyway, if this possibility happens the cache will
* be reset the next time that a persistent room is removed from memory.
*
* @author Gaston Dombiak
*/
public class MultiUserChatServerImpl extends BasicModule implements MultiUserChatServer,
ServerItemsProvider, DiscoInfoProvider, DiscoItemsProvider, RoutableChannelHandler {
/**
* The time to elapse between clearing of idle chat users.
*/
private static int USER_TIMEOUT = 300000;
/**
* The number of milliseconds a user must be idle before he/she gets kicked from all the rooms.
*/
private static int USER_IDLE = 1800000;
/**
* The time to elapse between logging the room conversations.
*/
private static int LOG_TIMEOUT = 300000;
/**
* The number of messages to log on each run of the logging process.
*/
private static int LOG_BATCH_SIZE = 50;
/**
* the chat service's hostname
*/
private String chatServiceName = null;
private XMPPAddress chatServiceAddress = null;
/**
* chatrooms managed by this manager, table: key room name (String); value ChatRoom
*/
private Map<String,MUCRoom> rooms = new ConcurrentHashMap<String,MUCRoom>();
/**
* chat users managed by this manager, table: key user jid (XMPPAddress); value ChatUser
*/
private Map<XMPPAddress, MUCUser> users = new ConcurrentHashMap<XMPPAddress, MUCUser>();
private HistoryStrategy historyStrategy;
private RoutingTable routingTable = null;
/**
* The packet deliverer for the server.
*/
public PacketDeliverer deliverer = null;
/**
* The packet router for the server.
*/
public PacketRouter router = null;
/**
* The packet manager for the server.
*/
public PresenceManager presenceManager = null;
/**
* The handler of packets with namespace jabber:iq:register for the server.
*/
public IQRegisterHandler registerHandler = null;
/**
* The total time all agents took to chat *
*/
public long totalChatTime;
/**
* Timer to monitor chatroom participants. If they've been idle for too long, probe for
* presence.
*/
private Timer timer = new Timer();
/**
* Returns the permission policy for creating rooms. A true value means that not anyone can
* create a room, only the JIDs listed in <code>allowedToCreate</code> are allowed to create
* rooms.
*/
private boolean roomCreationRestricted = false;
/**
* Bare jids of users that are allowed to create MUC rooms. An empty list means that anyone can
* create a room.
*/
private Collection<String> allowedToCreate = new CopyOnWriteArrayList<String>();
/**
* Bare jids of users that are system administrators of the MUC service. A sysadmin has the same
* permissions as a room owner.
*/
private Collection<String> sysadmins = new CopyOnWriteArrayList<String>();
/**
* Queue that holds the messages to log for the rooms that need to log their conversations.
*/
private Queue<ConversationLogEntry> logQueue = new LinkedBlockingQueue<ConversationLogEntry>();
/**
* Create a new group chat server.
*/
public MultiUserChatServerImpl() {
super("Basic multi user chat server");
historyStrategy = new HistoryStrategy(null);
}
/**
* Probes the presence of any user who's last packet was sent more than 5 minute ago.
*/
private class UserTimeoutTask extends TimerTask {
/**
* Remove any user that has been idle for longer than the user timeout time.
*/
public void run() {
checkForTimedOutUsers();
}
}
private void checkForTimedOutUsers() {
// Do nothing if this feature is disabled (i.e USER_IDLE equals -1)
if (USER_IDLE == -1) {
return;
}
final long deadline = System.currentTimeMillis() - USER_IDLE;
for (MUCUser user : users.values()) {
try {
if (user.getLastPacketTime() < deadline) {
// Kick the user from all the rooms that he/she had previuosly joined
Iterator<MUCRole> roles = user.getRoles();
MUCRole role;
MUCRoom room;
Presence kickedPresence;
while (roles.hasNext()) {
role = roles.next();
room = role.getChatRoom();
try {
kickedPresence =
room.kickOccupant(user.getAddress().toStringPrep(), null, null);
// Send the updated presence to the room occupants
room.send(kickedPresence);
}
catch (NotAllowedException e) {
// Do nothing since we cannot kick owners or admins
}
}
}
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
/**
* Logs the conversation of the rooms that have this feature enabled.
*/
private class LogConversationTask extends TimerTask {
public void run() {
try {
logConversation();
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
private void logConversation() {
ConversationLogEntry entry = null;
boolean success = false;
for (int index = 0; index <= LOG_BATCH_SIZE && !logQueue.isEmpty(); index++) {
entry = logQueue.poll();
if (entry != null) {
success = MUCPersistenceManager.saveConversationLogEntry(entry);
if (!success) {
logQueue.add(entry);
}
}
}
}
/**
* Logs all the remaining conversation log entries to the database. Use this method to force
* saving all the conversation log entries before the service becomes unavailable.
*/
private void logAllConversation() {
ConversationLogEntry entry = null;
while (!logQueue.isEmpty()) {
entry = logQueue.poll();
if (entry != null) {
MUCPersistenceManager.saveConversationLogEntry(entry);
}
}
}
public MUCRoom getChatRoom(String roomName, XMPPAddress userjid) throws UnauthorizedException {
MUCRoom room = null;
synchronized (rooms) {
room = rooms.get(roomName.toLowerCase());
if (room == null) {
room = new MUCRoomImpl(this, roomName, router);
// If the room is persistent load the configuration values from the DB
try {
// Try to load the room's configuration from the database (if the room is
// persistent but was added to the DB after the server was started up)
MUCPersistenceManager.loadFromDB(room);
}
catch (IllegalArgumentException e) {
// The room does not exist so check for creation permissions
// Room creation is always allowed for sysadmin
if (isRoomCreationRestricted() &&
!sysadmins.contains(userjid.toBareStringPrep())) {
// The room creation is only allowed for certain JIDs
if (!allowedToCreate.contains(userjid.toBareStringPrep())) {
// The user is not in the list of allowed JIDs to create a room so raise
// an exception
throw new UnauthorizedException();
}
}
room.addFirstOwner(userjid.toBareStringPrep());
}
rooms.put(roomName.toLowerCase(), room);
}
}
return room;
}
public MUCRoom getChatRoom(String roomName) {
return rooms.get(roomName.toLowerCase());
}
public List<MUCRoom> getChatRooms() {
return new ArrayList<MUCRoom>(rooms.values());
}
public boolean hasChatRoom(String roomName) {
return getChatRoom(roomName) != null;
}
public void removeChatRoom(String roomName) {
final MUCRoom room = rooms.remove(roomName.toLowerCase());
if (room != null) {
final long chatLength = room.getChatLength();
totalChatTime += chatLength;
}
}
public String getServiceName() {
return chatServiceName;
}
public HistoryStrategy getHistoryStrategy() {
return historyStrategy;
}
public void removeUser(XMPPAddress jabberID) {
MUCUser user = users.remove(jabberID);
if (user != null) {
Iterator<MUCRole> roles = user.getRoles();
while (roles.hasNext()) {
MUCRole role = roles.next();
try {
role.getChatRoom().leaveRoom(role.getNickname());
}
catch (Exception e) {
Log.error(e);
}
}
}
}
public MUCUser getChatUser(XMPPAddress userjid) throws UserNotFoundException {
if (router == null) {
throw new IllegalStateException("Not initialized");
}
MUCUser user = null;
synchronized (users) {
user = users.get(userjid);
if (user == null) {
user = new MUCUserImpl(this, router, userjid);
users.put(userjid, user);
}
}
return user;
}
public void serverBroadcast(String msg) throws UnauthorizedException {
for (MUCRoom room : rooms.values()) {
room.serverBroadcast(msg);
}
}
/**
* Initialize the track info for the server.
*
* @return the track information for this server.
*/
protected TrackInfo getTrackInfo() {
TrackInfo trackInfo = new TrackInfo();
trackInfo.getTrackerClasses().put(PacketRouter.class, "router");
trackInfo.getTrackerClasses().put(PacketDeliverer.class, "deliverer");
trackInfo.getTrackerClasses().put(PresenceManager.class, "presenceManager");
// TODO Remove the tracking for IQRegisterHandler when the component JEP gets implemented.
trackInfo.getTrackerClasses().put(IQRegisterHandler.class, "registerHandler");
return trackInfo;
}
public void serviceAdded(Object service) {
if (service instanceof RoutingTable) {
((RoutingTable)service).addRoute(chatServiceAddress, this);
ArrayList params = new ArrayList();
params.clear();
params.add(chatServiceName);
Log.info(LocaleUtils.getLocalizedString("startup.starting.muc", params));
}
else if (service instanceof IQRegisterHandler) {
((IQRegisterHandler) service).addDelegate(
getServiceName(),
new IQMUCRegisterHandler(this));
}
}
public void setServiceName(String name) {
JiveGlobals.setProperty("xmpp.muc.service", name);
}
public Collection<String> getUsersAllowedToCreate() {
return allowedToCreate;
}
public Collection<String> getSysadmins() {
return sysadmins;
}
public void addSysadmin(String userJID) {
sysadmins.add(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[sysadmins.size()];
jids = (String[])sysadmins.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.sysadmin.jid", fromArray(jids));
}
public void removeSysadmin(String userJID) {
sysadmins.remove(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[sysadmins.size()];
jids = (String[])sysadmins.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.sysadmin.jid", fromArray(jids));
}
public boolean isRoomCreationRestricted() {
return roomCreationRestricted;
}
public void setRoomCreationRestricted(boolean roomCreationRestricted) {
this.roomCreationRestricted = roomCreationRestricted;
JiveGlobals.setProperty("xmpp.muc.create.anyone", Boolean.toString(roomCreationRestricted));
}
public void addUserAllowedToCreate(String userJID) {
// Update the list of allowed JIDs to create MUC rooms. Since we are updating the instance
// variable there is no need to restart the service
allowedToCreate.add(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[allowedToCreate.size()];
jids = (String[])allowedToCreate.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.create.jid", fromArray(jids));
}
public void removeUserAllowedToCreate(String userJID) {
// Update the list of allowed JIDs to create MUC rooms. Since we are updating the instance
// variable there is no need to restart the service
allowedToCreate.remove(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[allowedToCreate.size()];
jids = (String[])allowedToCreate.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.create.jid", fromArray(jids));
}
public void initialize(Container container) {
super.initialize(container);
chatServiceName = JiveGlobals.getProperty("xmpp.muc.service");
// Trigger the strategy to load itself from the context
historyStrategy.setContext("xmpp.muc.history");
// Load the list of JIDs that are sysadmins of the MUC service
String property = JiveGlobals.getProperty("xmpp.muc.sysadmin.jid");
String[] jids;
if (property != null) {
jids = property.split(",");
for (int i = 0; i < jids.length; i++) {
sysadmins.add(jids[i].trim().toLowerCase());
}
}
roomCreationRestricted =
Boolean.parseBoolean(JiveGlobals.getProperty("xmpp.muc.create.anyone", "false"));
// Load the list of JIDs that are allowed to create a MUC room
property = JiveGlobals.getProperty("xmpp.muc.create.jid");
if (property != null) {
jids = property.split(",");
for (int i = 0; i < jids.length; i++) {
allowedToCreate.add(jids[i].trim().toLowerCase());
}
}
String value = JiveGlobals.getProperty("xmpp.muc.tasks.user.timeout");
if (value != null) {
try {
USER_TIMEOUT = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.user.timeout", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.user.idle");
if (value != null) {
try {
USER_IDLE = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.user.idle", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.log.timeout");
if (value != null) {
try {
LOG_TIMEOUT = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.log.timeout", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.log.batchsize");
if (value != null) {
try {
LOG_BATCH_SIZE = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.log.batchsize", e);
}
}
if (chatServiceName == null) {
chatServiceName = "conference";
}
String serverName = null;
try {
XMPPServer server = (XMPPServer)lookup.lookup(XMPPServer.class);
if (server != null) {
serverName = server.getServerInfo().getName();
}
else {
// Try to get serverName directly.
serverName = JiveGlobals.getProperty("xmpp.domain");
}
}
catch (Exception e) {
Log.error(e);
}
if (serverName != null) {
chatServiceName += "." + serverName;
}
chatServiceAddress = new XMPPAddress(null, chatServiceName, null);
// Run through the users every 5 minutes after a 5 minutes server startup delay (default
// values)
timer.schedule(new UserTimeoutTask(), USER_TIMEOUT, USER_TIMEOUT);
// Log the room conversations every 5 minutes after a 5 minutes server startup delay
// (default values)
timer.schedule(new LogConversationTask(), LOG_TIMEOUT, LOG_TIMEOUT);
}
public void start() {
super.start();
routingTable = (RoutingTable)lookup.lookup(RoutingTable.class);
routingTable.addRoute(chatServiceAddress, this);
ArrayList params = new ArrayList();
params.clear();
params.add(chatServiceName);
Log.info(LocaleUtils.getLocalizedString("startup.starting.muc", params));
// Load all the persistent rooms to memory
for (MUCRoom room : MUCPersistenceManager.loadRoomsFromDB(this, router)) {
rooms.put(room.getName().toLowerCase(), room);
}
}
public void stop() {
super.stop();
timer.cancel();
logAllConversation();
if (registerHandler != null) {
registerHandler.removeDelegate(getServiceName());
}
}
public XMPPAddress getAddress() {
if (chatServiceAddress == null) {
throw new IllegalStateException("Not initialized");
}
return chatServiceAddress;
}
public void process(XMPPPacket packet) {
try {
MUCUser user = getChatUser(packet.getSender());
user.process(packet);
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
public long getTotalChatTime() {
return totalChatTime;
}
public void logConversation(MUCRoom room, Message message, XMPPAddress sender) {
logQueue.add(new ConversationLogEntry(new Date(), room, message, sender));
}
public Iterator getItems() {
ArrayList items = new ArrayList();
items.add(new DiscoServerItem() {
public String getJID() {
return chatServiceName;
}
public String getName() {
return "Public Chatrooms";
}
public String getAction() {
return null;
}
public String getNode() {
return null;
}
public DiscoInfoProvider getDiscoInfoProvider() {
return MultiUserChatServerImpl.this;
}
public DiscoItemsProvider getDiscoItemsProvider() {
return MultiUserChatServerImpl.this;
}
});
return items.iterator();
}
public Iterator getIdentities(String name, String node, XMPPAddress senderJID) {
// TODO Improve performance by not creating objects each time
ArrayList identities = new ArrayList();
if (name == null && node == null) {
// Answer the identity of the MUC service
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", "Public Chatrooms");
identity.addAttribute("type", "text");
identities.add(identity);
}
else if (name != null && node == null) {
// Answer the identity of a given room
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", room.getNaturalLanguageName());
identity.addAttribute("type", "text");
identities.add(identity);
}
}
else if (name != null && "x-roomuser-item".equals(node)) {
// Answer reserved nickname for the sender of the disco request in the requested room
MUCRoom room = getChatRoom(name);
if (room != null) {
String reservedNick = room.getReservedNickname(senderJID.toBareStringPrep());
if (reservedNick != null) {
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", reservedNick);
identity.addAttribute("type", "text");
identities.add(identity);
}
}
}
return identities.iterator();
}
public Iterator getFeatures(String name, String node, XMPPAddress senderJID) {
ArrayList features = new ArrayList();
if (name == null && node == null) {
// Answer the features of the MUC service
features.add("http://jabber.org/protocol/muc");
features.add("http://jabber.org/protocol/disco#info");
features.add("http://jabber.org/protocol/disco#items");
}
else if (name != null && node == null) {
// Answer the features of a given room
// TODO lock the room while gathering this info???
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
features.add("http://jabber.org/protocol/muc");
// Always add public since only public rooms can be discovered
features.add("muc_public");
if (room.isInvitationRequiredToEnter()) {
features.add("muc_membersonly");
}
else {
features.add("muc_open");
}
if (room.isModerated()) {
features.add("muc_moderated");
}
else {
features.add("muc_unmoderated");
}
if (room.canAnyoneDiscoverJID()) {
features.add("muc_nonanonymous");
}
else {
features.add("muc_semianonymous");
}
if (room.isPasswordProtected()) {
features.add("muc_passwordprotected");
}
else {
features.add("muc_unsecured");
}
if (room.isPersistent()) {
features.add("muc_persistent");
}
else {
features.add("muc_temporary");
}
}
}
return features.iterator();
}
public XDataForm getExtendedInfo(String name, String node, XMPPAddress senderJID) {
if (name != null && node == null) {
// Answer the extended info of a given room
// TODO lock the room while gathering this info???
// TODO Do not generate a form each time. Keep it as static or instance variable
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
XDataFormImpl dataForm = new XDataFormImpl(DataForm.TYPE_RESULT);
XFormFieldImpl field = new XFormFieldImpl("FORM_TYPE");
field.setType(FormField.TYPE_HIDDEN);
field.addValue("http://jabber.org/protocol/muc#roominfo");
dataForm.addField(field);
field = new XFormFieldImpl("muc#roominfo_description");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.desc"));
field.addValue(room.getDescription());
dataForm.addField(field);
field = new XFormFieldImpl("muc#roominfo_subject");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.subject"));
field.addValue(room.getSubject());
dataForm.addField(field);
field = new XFormFieldImpl("muc#roominfo_occupants");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.occupants"));
field.addValue(Integer.toString(room.getOccupantsCount()));
dataForm.addField(field);
/*field = new XFormFieldImpl("muc#roominfo_lang");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.language"));
field.addValue(room.getLanguage());
dataForm.addField(field);*/
return dataForm;
}
}
return null;
}
public boolean hasInfo(String name, String node, XMPPAddress senderJID)
throws UnauthorizedException {
if (name == null && node == node) {
// We always have info about the MUC service
return true;
}
else if (name != null && node == null) {
// We only have info if the room exists
return hasChatRoom(name);
}
else if (name != null && "x-roomuser-item".equals(node)) {
// We always have info about reserved names as long as the room exists
return hasChatRoom(name);
}
return false;
}
public Iterator getItems(String name, String node, XMPPAddress senderJID)
throws UnauthorizedException {
List answer = new ArrayList();
if (name == null && node == null) {
Element item;
// Answer all the public rooms as items
for (MUCRoom room : rooms.values()) {
if (room.isPublicRoom()) {
item = DocumentHelper.createElement("item");
item.addAttribute("jid", room.getRole().getRoleAddress().toStringPrep());
item.addAttribute("name", room.getNaturalLanguageName());
answer.add(item);
}
}
}
else if (name != null && node == null) {
// Answer the room occupants as items if that info is publicly available
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
Element item;
for (MUCRole role : room.getOccupants()) {
// TODO Should we filter occupants that are invisible (presence is not broadcasted)?
item = DocumentHelper.createElement("item");
item.addAttribute("jid", role.getRoleAddress().toStringPrep());
answer.add(item);
}
}
}
return answer.iterator();
}
/**
* Converts an array to a comma-delimitted String.
*
* @param array the array.
* @return a comma delimtted String of the array values.
*/
private static String fromArray(String [] array) {
StringBuffer buf = new StringBuffer();
for (int i=0; i<array.length; i++) {
buf.append(array[i]);
if (i != array.length-1) {
buf.append(",");
}
}
return buf.toString();
}
}
|
src/java/org/jivesoftware/messenger/muc/spi/MultiUserChatServerImpl.java
|
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2004 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.messenger.muc.spi;
import org.jivesoftware.messenger.container.*;
import org.jivesoftware.messenger.disco.DiscoInfoProvider;
import org.jivesoftware.messenger.disco.DiscoItemsProvider;
import org.jivesoftware.messenger.disco.DiscoServerItem;
import org.jivesoftware.messenger.disco.ServerItemsProvider;
import org.jivesoftware.messenger.forms.DataForm;
import org.jivesoftware.messenger.forms.FormField;
import org.jivesoftware.messenger.forms.XDataForm;
import org.jivesoftware.messenger.forms.spi.XDataFormImpl;
import org.jivesoftware.messenger.forms.spi.XFormFieldImpl;
import org.jivesoftware.messenger.muc.*;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.handler.IQRegisterHandler;
import org.jivesoftware.messenger.user.UserNotFoundException;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* Implements the chat server as a cached memory resident chat server. The server is also
* responsible for responding Multi-User Chat disco requests as well as removing inactive users from
* the rooms after a period of time and to maintain a log of the conversation in the rooms that
* require to log their conversations. The conversations log is saved to the database using a
* separate process<p>
*
* Rooms in memory are held in the instance variable rooms. For optimization reasons, persistent
* rooms that don't have occupants aren't kept in memory. But a client may need to discover all the
* rooms (present in memory or not). So MultiUserChatServerImpl uses a cache of persistent room
* surrogates. A room surrogate (lighter object) is created for each persistent room that is public,
* persistent but is not in memory. The cache starts up empty until a client requests the list of
* rooms through service discovery. Once the disco request is received the cache is filled up with
* persistent room surrogates. The cache will keep all the surrogates in memory for an hour. If the
* cache's entries weren't used in an hour, they will be removed from memory. Whenever a persistent
* room is removed from memory (because all the occupants have left), the cache is cleared. But if
* a persistent room is loaded from the database then the entry for that room in the cache is
* removed. Note: Since the cache contains an entry for each room surrogate and the clearing
* algorithm is based on the usage of each entry, it's possible that some entries are removed
* while others don't thus generating that the provided list of discovered rooms won't be complete.
* However, this possibility is low since the clients will most of the time ask for all the cache
* entries and then ask for a particular entry. Anyway, if this possibility happens the cache will
* be reset the next time that a persistent room is removed from memory.
*
* @author Gaston Dombiak
*/
public class MultiUserChatServerImpl extends BasicModule implements MultiUserChatServer,
ServerItemsProvider, DiscoInfoProvider, DiscoItemsProvider, RoutableChannelHandler {
/**
* The time to elapse between clearing of idle chat users.
*/
private static int USER_TIMEOUT = 300000;
/**
* The number of milliseconds a user must be idle before he/she gets kicked from all the rooms.
*/
private static int USER_IDLE = 1800000;
/**
* The time to elapse between logging the room conversations.
*/
private static int LOG_TIMEOUT = 300000;
/**
* The number of messages to log on each run of the logging process.
*/
private static int LOG_BATCH_SIZE = 50;
/**
* the chat service's hostname
*/
private String chatServiceName = null;
private XMPPAddress chatServiceAddress = null;
/**
* chatrooms managed by this manager, table: key room name (String); value ChatRoom
*/
private Map<String,MUCRoom> rooms = new ConcurrentHashMap<String,MUCRoom>();
/**
* chat users managed by this manager, table: key user jid (XMPPAddress); value ChatUser
*/
private Map<XMPPAddress, MUCUser> users = new ConcurrentHashMap<XMPPAddress, MUCUser>();
private HistoryStrategy historyStrategy;
private RoutingTable routingTable = null;
/**
* The packet deliverer for the server.
*/
public PacketDeliverer deliverer = null;
/**
* The packet router for the server.
*/
public PacketRouter router = null;
/**
* The packet manager for the server.
*/
public PresenceManager presenceManager = null;
/**
* The handler of packets with namespace jabber:iq:register for the server.
*/
public IQRegisterHandler registerHandler = null;
/**
* The total time all agents took to chat *
*/
public long totalChatTime;
/**
* Timer to monitor chatroom participants. If they've been idle for too long, probe for
* presence.
*/
private Timer timer = new Timer();
/**
* Returns the permission policy for creating rooms. A true value means that not anyone can
* create a room, only the JIDs listed in <code>allowedToCreate</code> are allowed to create
* rooms.
*/
private boolean roomCreationRestricted = false;
/**
* Bare jids of users that are allowed to create MUC rooms. An empty list means that anyone can
* create a room.
*/
private Collection<String> allowedToCreate = new CopyOnWriteArrayList<String>();
/**
* Bare jids of users that are system administrators of the MUC service. A sysadmin has the same
* permissions as a room owner.
*/
private Collection<String> sysadmins = new CopyOnWriteArrayList<String>();
/**
* Queue that holds the messages to log for the rooms that need to log their conversations.
*/
private Queue<ConversationLogEntry> logQueue = new LinkedBlockingQueue<ConversationLogEntry>();
/**
* Create a new group chat server.
*/
public MultiUserChatServerImpl() {
super("Basic multi user chat server");
historyStrategy = new HistoryStrategy(null);
}
/**
* Probes the presence of any user who's last packet was sent more than 5 minute ago.
*/
private class UserTimeoutTask extends TimerTask {
/**
* Remove any user that has been idle for longer than the user timeout time.
*/
public void run() {
checkForTimedOutUsers();
}
}
private void checkForTimedOutUsers() {
// Do nothing if this feature is disabled (i.e USER_IDLE equals -1)
if (USER_IDLE == -1) {
return;
}
final long deadline = System.currentTimeMillis() - USER_IDLE;
for (MUCUser user : users.values()) {
try {
if (user.getLastPacketTime() < deadline) {
// Kick the user from all the rooms that he/she had previuosly joined
Iterator<MUCRole> roles = user.getRoles();
MUCRole role;
MUCRoom room;
Presence kickedPresence;
while (roles.hasNext()) {
role = roles.next();
room = role.getChatRoom();
try {
kickedPresence =
room.kickOccupant(user.getAddress().toStringPrep(), null, null);
// Send the updated presence to the room occupants
room.send(kickedPresence);
}
catch (NotAllowedException e) {
// Do nothing since we cannot kick owners or admins
}
}
}
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
/**
* Logs the conversation of the rooms that have this feature enabled.
*/
private class LogConversationTask extends TimerTask {
public void run() {
try {
logConversation();
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
}
private void logConversation() {
ConversationLogEntry entry = null;
boolean success = false;
for (int index = 0; index <= LOG_BATCH_SIZE && !logQueue.isEmpty(); index++) {
entry = logQueue.poll();
if (entry != null) {
success = MUCPersistenceManager.saveConversationLogEntry(entry);
if (!success) {
logQueue.add(entry);
}
}
}
}
/**
* Logs all the remaining conversation log entries to the database. Use this method to force
* saving all the conversation log entries before the service becomes unavailable.
*/
private void logAllConversation() {
ConversationLogEntry entry = null;
while (!logQueue.isEmpty()) {
entry = logQueue.poll();
if (entry != null) {
MUCPersistenceManager.saveConversationLogEntry(entry);
}
}
}
public MUCRoom getChatRoom(String roomName, XMPPAddress userjid) throws UnauthorizedException {
MUCRoom room = null;
synchronized (rooms) {
room = rooms.get(roomName.toLowerCase());
if (room == null) {
room = new MUCRoomImpl(this, roomName, router);
// If the room is persistent load the configuration values from the DB
try {
// Try to load the room's configuration from the database (if the room is
// persistent but was added to the DB after the server was started up)
MUCPersistenceManager.loadFromDB(room);
}
catch (IllegalArgumentException e) {
// The room does not exist so check for creation permissions
// Room creation is always allowed for sysadmin
if (isRoomCreationRestricted() &&
!sysadmins.contains(userjid.toBareStringPrep())) {
// The room creation is only allowed for certain JIDs
if (!allowedToCreate.contains(userjid.toBareStringPrep())) {
// The user is not in the list of allowed JIDs to create a room so raise
// an exception
throw new UnauthorizedException();
}
}
room.addFirstOwner(userjid.toBareStringPrep());
}
rooms.put(roomName.toLowerCase(), room);
}
}
return room;
}
public MUCRoom getChatRoom(String roomName) {
return rooms.get(roomName.toLowerCase());
}
public List<MUCRoom> getChatRooms() {
return new ArrayList<MUCRoom>(rooms.values());
}
public boolean hasChatRoom(String roomName) {
return getChatRoom(roomName) != null;
}
public void removeChatRoom(String roomName) {
final MUCRoom room = rooms.remove(roomName.toLowerCase());
if (room != null) {
final long chatLength = room.getChatLength();
totalChatTime += chatLength;
}
}
public String getServiceName() {
return chatServiceName;
}
public HistoryStrategy getHistoryStrategy() {
return historyStrategy;
}
public void removeUser(XMPPAddress jabberID) {
MUCUser user = users.remove(jabberID);
if (user != null) {
Iterator<MUCRole> roles = user.getRoles();
while (roles.hasNext()) {
MUCRole role = roles.next();
try {
role.getChatRoom().leaveRoom(role.getNickname());
}
catch (Exception e) {
Log.error(e);
}
}
}
}
public MUCUser getChatUser(XMPPAddress userjid) throws UserNotFoundException {
if (router == null) {
throw new IllegalStateException("Not initialized");
}
MUCUser user = null;
synchronized (users) {
user = users.get(userjid);
if (user == null) {
user = new MUCUserImpl(this, router, userjid);
users.put(userjid, user);
}
}
return user;
}
public void serverBroadcast(String msg) throws UnauthorizedException {
for (MUCRoom room : rooms.values()) {
room.serverBroadcast(msg);
}
}
/**
* Initialize the track info for the server.
*
* @return the track information for this server.
*/
protected TrackInfo getTrackInfo() {
TrackInfo trackInfo = new TrackInfo();
trackInfo.getTrackerClasses().put(PacketRouter.class, "router");
trackInfo.getTrackerClasses().put(PacketDeliverer.class, "deliverer");
trackInfo.getTrackerClasses().put(PresenceManager.class, "presenceManager");
// TODO Remove the tracking for IQRegisterHandler when the component JEP gets implemented.
trackInfo.getTrackerClasses().put(IQRegisterHandler.class, "registerHandler");
return trackInfo;
}
public void serviceAdded(Object service) {
if (service instanceof RoutingTable) {
((RoutingTable)service).addRoute(chatServiceAddress, this);
ArrayList params = new ArrayList();
params.clear();
params.add(chatServiceName);
Log.info(LocaleUtils.getLocalizedString("startup.starting.muc", params));
}
else if (service instanceof IQRegisterHandler) {
((IQRegisterHandler) service).addDelegate(
getServiceName(),
new IQMUCRegisterHandler(this));
}
}
public void setServiceName(String name) {
JiveGlobals.setProperty("xmpp.muc.service", name);
}
public Collection<String> getUsersAllowedToCreate() {
return allowedToCreate;
}
public Collection<String> getSysadmins() {
return sysadmins;
}
public void addSysadmin(String userJID) {
sysadmins.add(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[sysadmins.size()];
jids = (String[])sysadmins.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.sysadmin.jid", fromArray(jids));
}
public void removeSysadmin(String userJID) {
sysadmins.remove(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[sysadmins.size()];
jids = (String[])sysadmins.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.sysadmin.jid", fromArray(jids));
}
public boolean isRoomCreationRestricted() {
return roomCreationRestricted;
}
public void setRoomCreationRestricted(boolean roomCreationRestricted) {
this.roomCreationRestricted = roomCreationRestricted;
JiveGlobals.setProperty("xmpp.muc.create.anyone", Boolean.toString(roomCreationRestricted));
}
public void addUserAllowedToCreate(String userJID) {
// Update the list of allowed JIDs to create MUC rooms. Since we are updating the instance
// variable there is no need to restart the service
allowedToCreate.add(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[allowedToCreate.size()];
jids = (String[])allowedToCreate.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.create.jid", fromArray(jids));
}
public void removeUserAllowedToCreate(String userJID) {
// Update the list of allowed JIDs to create MUC rooms. Since we are updating the instance
// variable there is no need to restart the service
allowedToCreate.remove(userJID.trim().toLowerCase());
// Update the config.
String[] jids = new String[allowedToCreate.size()];
jids = (String[])allowedToCreate.toArray(jids);
JiveGlobals.setProperty("xmpp.muc.create.jid", fromArray(jids));
}
public void initialize(Container container) {
super.initialize(container);
chatServiceName = JiveGlobals.getProperty("xmpp.muc.service");
// Trigger the strategy to load itself from the context
historyStrategy.setContext("xmpp.muc.history");
// Load the list of JIDs that are sysadmins of the MUC service
String property = JiveGlobals.getProperty("xmpp.muc.sysadmin.jid");
String[] jids;
if (property != null) {
jids = property.split(",");
for (int i = 0; i < jids.length; i++) {
sysadmins.add(jids[i].trim().toLowerCase());
}
}
roomCreationRestricted =
Boolean.parseBoolean(JiveGlobals.getProperty("xmpp.muc.create.anyone", "false"));
// Load the list of JIDs that are allowed to create a MUC room
property = JiveGlobals.getProperty("xmpp.muc.create.jid");
if (property != null) {
jids = property.split(",");
for (int i = 0; i < jids.length; i++) {
allowedToCreate.add(jids[i].trim().toLowerCase());
}
}
String value = JiveGlobals.getProperty("xmpp.muc.tasks.user.timeout");
if (value != null) {
try {
USER_TIMEOUT = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.user.timeout", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.user.idle");
if (value != null) {
try {
USER_IDLE = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.user.idle", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.log.timeout");
if (value != null) {
try {
LOG_TIMEOUT = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.log.timeout", e);
}
}
value = JiveGlobals.getProperty("xmpp.muc.tasks.log.batchsize");
if (value != null) {
try {
LOG_BATCH_SIZE = Integer.parseInt(value);
}
catch (NumberFormatException e) {
Log.error("Wrong number format of property xmpp.muc.tasks.log.batchsize", e);
}
}
if (chatServiceName == null) {
chatServiceName = "conference";
}
String serverName = null;
try {
XMPPServer server = (XMPPServer)lookup.lookup(XMPPServer.class);
if (server != null) {
serverName = server.getServerInfo().getName();
}
else {
// Try to get serverName directly.
serverName = JiveGlobals.getProperty("xmpp.domain");
}
}
catch (Exception e) {
Log.error(e);
}
if (serverName != null) {
chatServiceName += "." + serverName;
}
chatServiceAddress = new XMPPAddress(null, chatServiceName, null);
// Run through the users every 5 minutes after a 5 minutes server startup delay (default
// values)
timer.schedule(new UserTimeoutTask(), USER_TIMEOUT, USER_TIMEOUT);
// Log the room conversations every 5 minutes after a 5 minutes server startup delay
// (default values)
timer.schedule(new LogConversationTask(), LOG_TIMEOUT, LOG_TIMEOUT);
}
public void start() {
super.start();
routingTable = (RoutingTable)lookup.lookup(RoutingTable.class);
routingTable.addRoute(chatServiceAddress, this);
ArrayList params = new ArrayList();
params.clear();
params.add(chatServiceName);
Log.info(LocaleUtils.getLocalizedString("startup.starting.muc", params));
// Load all the persistent rooms to memory
for (MUCRoom room : MUCPersistenceManager.loadRoomsFromDB(this, router)) {
rooms.put(room.getName().toLowerCase(), room);
}
}
public void stop() {
super.stop();
timer.cancel();
logAllConversation();
if (registerHandler != null) {
registerHandler.removeDelegate(getServiceName());
}
}
public XMPPAddress getAddress() {
if (chatServiceAddress == null) {
throw new IllegalStateException("Not initialized");
}
return chatServiceAddress;
}
public void process(XMPPPacket packet) {
try {
MUCUser user = getChatUser(packet.getSender());
user.process(packet);
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
public long getTotalChatTime() {
return totalChatTime;
}
public void logConversation(MUCRoom room, Message message, XMPPAddress sender) {
logQueue.add(new ConversationLogEntry(new Date(), room, message, sender));
}
public Iterator getItems() {
ArrayList items = new ArrayList();
items.add(new DiscoServerItem() {
public String getJID() {
return chatServiceName;
}
public String getName() {
return "Public Chatrooms";
}
public String getAction() {
return null;
}
public String getNode() {
return null;
}
public DiscoInfoProvider getDiscoInfoProvider() {
return MultiUserChatServerImpl.this;
}
public DiscoItemsProvider getDiscoItemsProvider() {
return MultiUserChatServerImpl.this;
}
});
return items.iterator();
}
public Iterator getIdentities(String name, String node, XMPPAddress senderJID) {
// TODO Improve performance by not creating objects each time
ArrayList identities = new ArrayList();
if (name == null && node == null) {
// Answer the identity of the MUC service
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", "Public Chatrooms");
identity.addAttribute("type", "text");
identities.add(identity);
}
else if (name != null && node == null) {
// Answer the identity of a given room
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", room.getNaturalLanguageName());
identity.addAttribute("type", "text");
identities.add(identity);
}
}
else if (name != null && "x-roomuser-item".equals(node)) {
// Answer reserved nickname for the sender of the disco request in the requested room
MUCRoom room = getChatRoom(name);
if (room != null) {
String reservedNick = room.getReservedNickname(senderJID.toBareStringPrep());
if (reservedNick != null) {
Element identity = DocumentHelper.createElement("identity");
identity.addAttribute("category", "conference");
identity.addAttribute("name", reservedNick);
identity.addAttribute("type", "text");
identities.add(identity);
}
}
}
return identities.iterator();
}
public Iterator getFeatures(String name, String node, XMPPAddress senderJID) {
ArrayList features = new ArrayList();
if (name == null && node == null) {
// Answer the features of the MUC service
features.add("http://jabber.org/protocol/muc");
features.add("http://jabber.org/protocol/disco#info");
features.add("http://jabber.org/protocol/disco#items");
}
else if (name != null && node == null) {
// Answer the features of a given room
// TODO lock the room while gathering this info???
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
features.add("http://jabber.org/protocol/muc");
// Always add public since only public rooms can be discovered
features.add("muc_public");
if (room.isInvitationRequiredToEnter()) {
features.add("muc_membersonly");
}
else {
features.add("muc_open");
}
if (room.isModerated()) {
features.add("muc_moderated");
}
else {
features.add("muc_unmoderated");
}
if (room.canAnyoneDiscoverJID()) {
features.add("muc_nonanonymous");
}
else {
features.add("muc_semianonymous");
}
if (room.isPasswordProtected()) {
features.add("muc_passwordprotected");
}
else {
features.add("muc_unsecured");
}
if (room.isPersistent()) {
features.add("muc_persistent");
}
else {
features.add("muc_temporary");
}
}
}
return features.iterator();
}
public XDataForm getExtendedInfo(String name, String node, XMPPAddress senderJID) {
if (name != null && node == null) {
// Answer the extended info of a given room
// TODO lock the room while gathering this info???
// TODO Do not generate a form each time. Keep it as static or instance variable
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
XDataFormImpl dataForm = new XDataFormImpl(DataForm.TYPE_RESULT);
XFormFieldImpl field = new XFormFieldImpl("FORM_TYPE");
field.setType(FormField.TYPE_HIDDEN);
field.addValue("http://jabber.org/protocol/muc#roominfo");
dataForm.addField(field);
field = new XFormFieldImpl("muc#roominfo_description");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.desc"));
field.addValue(room.getDescription());
dataForm.addField(field);
field = new XFormFieldImpl("muc#roominfo_subject");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.subject"));
field.addValue(room.getSubject());
dataForm.addField(field);
field = new XFormFieldImpl("muc#roominfo_occupants");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.occupants"));
field.addValue(Integer.toString(room.getOccupantsCount()));
dataForm.addField(field);
/*field = new XFormFieldImpl("muc#roominfo_lang");
field.setLabel(LocaleUtils.getLocalizedString("muc.extended.info.language"));
field.addValue(room.getLanguage());
dataForm.addField(field);*/
return dataForm;
}
}
return null;
}
public boolean hasInfo(String name, String node, XMPPAddress senderJID)
throws UnauthorizedException {
if (name == null && node == node) {
// We always have info about the MUC service
return true;
}
else if (name != null && node == null) {
// We only have info if the room exists
return hasChatRoom(name);
}
else if (name != null && "x-roomuser-item".equals(node)) {
// We always have info about reserved names as long as the room exists
return hasChatRoom(name);
}
return false;
}
public Iterator getItems(String name, String node, XMPPAddress senderJID)
throws UnauthorizedException {
List answer = new ArrayList();
if (name == null && node == null) {
Element item;
// Answer all the public rooms as items
for (MUCRoom room : rooms.values()) {
if (room.isPublicRoom()) {
item = DocumentHelper.createElement("item");
item.addAttribute("jid", room.getRole().getRoleAddress().toStringPrep());
item.addAttribute("name", room.getNaturalLanguageName());
answer.add(item);
}
}
}
else if (name != null && node == null) {
// Answer the room occupants as items if that info is publicly available
MUCRoom room = getChatRoom(name);
if (room != null && room.isPublicRoom()) {
MUCRole role;
Element item;
for (Iterator<MUCRole> members = room.getOccupants(); members.hasNext();) {
// TODO Should we filter occupants that are invisible (presence is not broadcasted)?
role = members.next();
item = DocumentHelper.createElement("item");
item.addAttribute("jid", role.getRoleAddress().toStringPrep());
answer.add(item);
}
}
}
return answer.iterator();
}
/**
* Converts an array to a comma-delimitted String.
*
* @param array the array.
* @return a comma delimtted String of the array values.
*/
private static String fromArray(String [] array) {
StringBuffer buf = new StringBuffer();
for (int i=0; i<array.length; i++) {
buf.append(array[i]);
if (i != array.length-1) {
buf.append(",");
}
}
return buf.toString();
}
}
|
Modified methods that were receiveing an Iterator to receive a Collection.
git-svn-id: 036f06d8526d2d198eab1b7c5596fd12295db076@496 b35dd754-fafc-0310-a699-88a17e54d16e
|
src/java/org/jivesoftware/messenger/muc/spi/MultiUserChatServerImpl.java
|
Modified methods that were receiveing an Iterator to receive a Collection.
|
<ide><path>rc/java/org/jivesoftware/messenger/muc/spi/MultiUserChatServerImpl.java
<ide> // Answer the room occupants as items if that info is publicly available
<ide> MUCRoom room = getChatRoom(name);
<ide> if (room != null && room.isPublicRoom()) {
<del> MUCRole role;
<ide> Element item;
<del> for (Iterator<MUCRole> members = room.getOccupants(); members.hasNext();) {
<add> for (MUCRole role : room.getOccupants()) {
<ide> // TODO Should we filter occupants that are invisible (presence is not broadcasted)?
<del> role = members.next();
<ide> item = DocumentHelper.createElement("item");
<ide> item.addAttribute("jid", role.getRoleAddress().toStringPrep());
<ide>
|
|
Java
|
apache-2.0
|
e0e039d7998a1cbf8a5d88bc7b01965e4e19b51d
| 0 |
apache/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,kalaspuffar/pdfbox
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.util;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSFloat;
import org.apache.pdfbox.cos.COSNumber;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.Arrays;
import org.apache.pdfbox.cos.COSBase;
/**
* This class will be used for matrix manipulation.
*
* @author Ben Litchfield
*/
public final class Matrix implements Cloneable
{
static final float[] DEFAULT_SINGLE =
{
1,0,0, // a b 0 sx hy 0 note: hx and hy are reversed vs. the PDF spec as we use
0,1,0, // c d 0 = hx sy 0 AffineTransform's definition x and y shear
0,0,1 // tx ty 1 tx ty 1
};
private final float[] single;
/**
* Constructor. This produces an identity matrix.
*/
public Matrix()
{
single = new float[DEFAULT_SINGLE.length];
System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length);
}
/**
* Creates a matrix from a 6-element (a b c d e f) COS array.
*
* @param array
*/
public Matrix(COSArray array)
{
single = new float[DEFAULT_SINGLE.length];
single[0] = ((COSNumber)array.getObject(0)).floatValue();
single[1] = ((COSNumber)array.getObject(1)).floatValue();
single[3] = ((COSNumber)array.getObject(2)).floatValue();
single[4] = ((COSNumber)array.getObject(3)).floatValue();
single[6] = ((COSNumber)array.getObject(4)).floatValue();
single[7] = ((COSNumber)array.getObject(5)).floatValue();
single[8] = 1;
}
/**
* Creates a transformation matrix with the given 6 elements. Transformation matrices are
* discussed in 8.3.3, "Common Transformations" and 8.3.4, "Transformation Matrices" of the PDF
* specification. For simple purposes (rotate, scale, translate) it is recommended to use the
* static methods below.
*
* @see Matrix#getRotateInstance(double, float, float)
* @see Matrix#getScaleInstance(float, float)
* @see Matrix#getTranslateInstance(float, float)
*
* @param a the X coordinate scaling element (m00) of the 3x3 matrix
* @param b the Y coordinate shearing element (m10) of the 3x3 matrix
* @param c the X coordinate shearing element (m01) of the 3x3 matrix
* @param d the Y coordinate scaling element (m11) of the 3x3 matrix
* @param e the X coordinate translation element (m02) of the 3x3 matrix
* @param f the Y coordinate translation element (m12) of the 3x3 matrix
*/
public Matrix(float a, float b, float c, float d, float e, float f)
{
single = new float[DEFAULT_SINGLE.length];
single[0] = a;
single[1] = b;
single[3] = c;
single[4] = d;
single[6] = e;
single[7] = f;
single[8] = 1;
}
/**
* Creates a matrix with the same elements as the given AffineTransform.
* @param at
*/
public Matrix(AffineTransform at)
{
single = new float[DEFAULT_SINGLE.length];
System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length);
single[0] = (float)at.getScaleX();
single[1] = (float)at.getShearY();
single[3] = (float)at.getShearX();
single[4] = (float)at.getScaleY();
single[6] = (float)at.getTranslateX();
single[7] = (float)at.getTranslateY();
}
/**
* Convenience method to be used when creating a matrix from unverified data. If the parameter
* is a COSArray with at least six numbers, a Matrix object is created from the first six
* numbers and returned. If not, then the identity Matrix is returned.
*
* @param base a COS object, preferably a COSArray with six numbers.
*
* @return a Matrix object.
*/
public static Matrix createMatrix(COSBase base)
{
if (!(base instanceof COSArray))
{
return new Matrix();
}
COSArray array = (COSArray) base;
if (array.size() < 6)
{
return new Matrix();
}
for (int i = 0; i < 6; ++i)
{
if (!(array.getObject(i) instanceof COSNumber))
{
return new Matrix();
}
}
return new Matrix(array);
}
/**
* This method resets the numbers in this Matrix to the original values, which are
* the values that a newly constructed Matrix would have.
*
* @deprecated This method will be removed.
*/
@Deprecated
public void reset()
{
System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length);
}
/**
* Create an affine transform from this matrix's values.
*
* @return An affine transform with this matrix's values.
*/
public AffineTransform createAffineTransform()
{
return new AffineTransform(
single[0], single[1], // m00 m10 = scaleX shearY
single[3], single[4], // m01 m11 = shearX scaleY
single[6], single[7] ); // m02 m12 = tx ty
}
/**
* Set the values of the matrix from the AffineTransform.
*
* @param af The transform to get the values from.
* @deprecated Use the {@link #Matrix(AffineTransform)} constructor instead.
*/
@Deprecated
public void setFromAffineTransform( AffineTransform af )
{
single[0] = (float)af.getScaleX();
single[1] = (float)af.getShearY();
single[3] = (float)af.getShearX();
single[4] = (float)af.getScaleY();
single[6] = (float)af.getTranslateX();
single[7] = (float)af.getTranslateY();
}
/**
* This will get a matrix value at some point.
*
* @param row The row to get the value from.
* @param column The column to get the value from.
*
* @return The value at the row/column position.
*/
public float getValue( int row, int column )
{
return single[row*3+column];
}
/**
* This will set a value at a position.
*
* @param row The row to set the value at.
* @param column the column to set the value at.
* @param value The value to set at the position.
*/
public void setValue( int row, int column, float value )
{
single[row*3+column] = value;
}
/**
* Return a single dimension array of all values in the matrix.
*
* @return The values of this matrix.
*/
public float[][] getValues()
{
float[][] retval = new float[3][3];
retval[0][0] = single[0];
retval[0][1] = single[1];
retval[0][2] = single[2];
retval[1][0] = single[3];
retval[1][1] = single[4];
retval[1][2] = single[5];
retval[2][0] = single[6];
retval[2][1] = single[7];
retval[2][2] = single[8];
return retval;
}
/**
* Return a single dimension array of all values in the matrix.
*
* @return The values ot this matrix.
* @deprecated Use {@link #getValues()} instead.
*/
@Deprecated
public double[][] getValuesAsDouble()
{
double[][] retval = new double[3][3];
retval[0][0] = single[0];
retval[0][1] = single[1];
retval[0][2] = single[2];
retval[1][0] = single[3];
retval[1][1] = single[4];
retval[1][2] = single[5];
retval[2][0] = single[6];
retval[2][1] = single[7];
retval[2][2] = single[8];
return retval;
}
/**
* Concatenates (premultiplies) the given matrix to this matrix.
*
* @param matrix The matrix to concatenate.
*/
public void concatenate(Matrix matrix)
{
matrix.multiply(this, this);
}
/**
* Translates this matrix by the given vector.
*
* @param vector 2D vector
*/
public void translate(Vector vector)
{
Matrix m = Matrix.getTranslateInstance(vector.getX(), vector.getY());
concatenate(m);
}
/**
* Translates this matrix by the given ammount.
*
* @param tx x-translation
* @param ty y-translation
*/
public void translate(float tx, float ty)
{
Matrix m = Matrix.getTranslateInstance(tx, ty);
concatenate(m);
}
/**
* Scales this matrix by the given factors.
*
* @param sx x-scale
* @param sy y-scale
*/
public void scale(float sx, float sy)
{
Matrix m = Matrix.getScaleInstance(sx, sy);
concatenate(m);
}
/**
* Rotares this matrix by the given factors.
*
* @param theta The angle of rotation measured in radians
*/
public void rotate(double theta)
{
Matrix m = Matrix.getRotateInstance(theta, 0, 0);
concatenate(m);
}
/**
* This will take the current matrix and multiply it with a matrix that is passed in.
*
* @param b The matrix to multiply by.
*
* @return The result of the two multiplied matrices.
*/
public Matrix multiply( Matrix b )
{
return this.multiply(b, new Matrix());
}
/**
* This method multiplies this Matrix with the specified other Matrix, storing the product in the specified
* result Matrix. By reusing Matrix instances like this, multiplication chains can be executed without having
* to create many temporary Matrix objects.
* <p>
* It is allowed to have (other == this) or (result == this) or indeed (other == result) but if this is done,
* the backing float[] matrix values may be copied in order to ensure a correct product.
*
* @param other the second operand Matrix in the multiplication
* @param result the Matrix instance into which the result should be stored. If result is null, a new Matrix
* instance is created.
* @return the product of the two matrices.
*/
public Matrix multiply( Matrix other, Matrix result )
{
if (result == null)
{
result = new Matrix();
}
if (other != null && other.single != null)
{
// the operands
float[] thisOperand = this.single;
float[] otherOperand = other.single;
// We're multiplying 2 sets of floats together to produce a third, but we allow
// any of these float[] instances to be the same objects.
// There is the possibility then to overwrite one of the operands with result values
// and therefore corrupt the result.
// If either of these operands are the same float[] instance as the result, then
// they need to be copied.
if (this == result)
{
final float[] thisOrigVals = new float[this.single.length];
System.arraycopy(this.single, 0, thisOrigVals, 0, this.single.length);
thisOperand = thisOrigVals;
}
if (other == result)
{
final float[] otherOrigVals = new float[other.single.length];
System.arraycopy(other.single, 0, otherOrigVals, 0, other.single.length);
otherOperand = otherOrigVals;
}
result.single[0] = thisOperand[0] * otherOperand[0]
+ thisOperand[1] * otherOperand[3]
+ thisOperand[2] * otherOperand[6];
result.single[1] = thisOperand[0] * otherOperand[1]
+ thisOperand[1] * otherOperand[4]
+ thisOperand[2] * otherOperand[7];
result.single[2] = thisOperand[0] * otherOperand[2]
+ thisOperand[1] * otherOperand[5]
+ thisOperand[2] * otherOperand[8];
result.single[3] = thisOperand[3] * otherOperand[0]
+ thisOperand[4] * otherOperand[3]
+ thisOperand[5] * otherOperand[6];
result.single[4] = thisOperand[3] * otherOperand[1]
+ thisOperand[4] * otherOperand[4]
+ thisOperand[5] * otherOperand[7];
result.single[5] = thisOperand[3] * otherOperand[2]
+ thisOperand[4] * otherOperand[5]
+ thisOperand[5] * otherOperand[8];
result.single[6] = thisOperand[6] * otherOperand[0]
+ thisOperand[7] * otherOperand[3]
+ thisOperand[8] * otherOperand[6];
result.single[7] = thisOperand[6] * otherOperand[1]
+ thisOperand[7] * otherOperand[4]
+ thisOperand[8] * otherOperand[7];
result.single[8] = thisOperand[6] * otherOperand[2]
+ thisOperand[7] * otherOperand[5]
+ thisOperand[8] * otherOperand[8];
}
return result;
}
/**
* Transforms the given point by this matrix.
*
* @param point point to transform
*/
public void transform(Point2D point)
{
float x = (float)point.getX();
float y = (float)point.getY();
float a = single[0];
float b = single[1];
float c = single[3];
float d = single[4];
float e = single[6];
float f = single[7];
point.setLocation(x * a + y * c + e, x * b + y * d + f);
}
/**
* Transforms the given point by this matrix.
*
* @param x x-coordinate
* @param y y-coordinate
*/
public Point2D.Float transformPoint(float x, float y)
{
float a = single[0];
float b = single[1];
float c = single[3];
float d = single[4];
float e = single[6];
float f = single[7];
return new Point2D.Float(x * a + y * c + e, x * b + y * d + f);
}
/**
* Transforms the given point by this matrix.
*
* @param vector 2D vector
*/
public Vector transform(Vector vector)
{
float a = single[0];
float b = single[1];
float c = single[3];
float d = single[4];
float e = single[6];
float f = single[7];
float x = vector.getX();
float y = vector.getY();
return new Vector(x * a + y * c + e, x * b + y * d + f);
}
/**
* Create a new matrix with just the scaling operators.
*
* @return A new matrix with just the scaling operators.
* @deprecated This method is due to be removed, please contact us if you make use of it.
*/
@Deprecated
public Matrix extractScaling()
{
Matrix matrix = new Matrix();
matrix.single[0] = this.single[0];
matrix.single[4] = this.single[4];
return matrix;
}
/**
* Convenience method to create a scaled instance.
*
* @param sx The xscale operator.
* @param sy The yscale operator.
* @return A new matrix with just the x/y scaling
*/
public static Matrix getScaleInstance(float sx, float sy)
{
Matrix matrix = new Matrix();
matrix.single[0] = sx;
matrix.single[4] = sy;
return matrix;
}
/**
* Create a new matrix with just the translating operators.
*
* @return A new matrix with just the translating operators.
* @deprecated This method is due to be removed, please contact us if you make use of it.
*/
@Deprecated
public Matrix extractTranslating()
{
Matrix matrix = new Matrix();
matrix.single[6] = this.single[6];
matrix.single[7] = this.single[7];
return matrix;
}
/**
* Convenience method to create a translating instance.
*
* @param tx The x translating operator.
* @param ty The y translating operator.
* @return A new matrix with just the x/y translating.
* @deprecated Use {@link #getTranslateInstance} instead.
*/
@Deprecated
public static Matrix getTranslatingInstance(float tx, float ty)
{
return getTranslateInstance(tx, ty);
}
/**
* Convenience method to create a translating instance.
*
* @param tx The x translating operator.
* @param ty The y translating operator.
* @return A new matrix with just the x/y translating.
*/
public static Matrix getTranslateInstance(float tx, float ty)
{
Matrix matrix = new Matrix();
matrix.single[6] = tx;
matrix.single[7] = ty;
return matrix;
}
/**
* Convenience method to create a rotated instance.
*
* @param theta The angle of rotation measured in radians
* @param tx The x translation.
* @param ty The y translation.
* @return A new matrix with the rotation and the x/y translating.
*/
public static Matrix getRotateInstance(double theta, float tx, float ty)
{
float cosTheta = (float)Math.cos(theta);
float sinTheta = (float)Math.sin(theta);
Matrix matrix = new Matrix();
matrix.single[0] = cosTheta;
matrix.single[1] = sinTheta;
matrix.single[3] = -sinTheta;
matrix.single[4] = cosTheta;
matrix.single[6] = tx;
matrix.single[7] = ty;
return matrix;
}
/**
* Produces a copy of the first matrix, with the second matrix concatenated.
*
* @param a The matrix to copy.
* @param b The matrix to concatenate.
*/
public static Matrix concatenate(Matrix a, Matrix b)
{
Matrix copy = a.clone();
copy.concatenate(b);
return copy;
}
/**
* Clones this object.
* @return cloned matrix as an object.
*/
@Override
public Matrix clone()
{
Matrix clone = new Matrix();
System.arraycopy( single, 0, clone.single, 0, 9 );
return clone;
}
/**
* Returns the x-scaling factor of this matrix. This is calculated from the scale and shear.
*
* @return The x-scaling factor.
*/
public float getScalingFactorX()
{
float xScale = single[0];
/**
* BM: if the trm is rotated, the calculation is a little more complicated
*
* The rotation matrix multiplied with the scaling matrix is:
* ( x 0 0) ( cos sin 0) ( x*cos x*sin 0)
* ( 0 y 0) * (-sin cos 0) = (-y*sin y*cos 0)
* ( 0 0 1) ( 0 0 1) ( 0 0 1)
*
* So, if you want to deduce x from the matrix you take
* M(0,0) = x*cos and M(0,1) = x*sin and use the theorem of Pythagoras
*
* sqrt(M(0,0)^2+M(0,1)^2) =
* sqrt(x2*cos2+x2*sin2) =
* sqrt(x2*(cos2+sin2)) = <- here is the trick cos2+sin2 is one
* sqrt(x2) =
* abs(x)
*/
if( !(Float.compare(single[1], 0.0f) == 0 && Float.compare(single[3], 0.0f) ==0) )
{
xScale = (float)Math.sqrt(Math.pow(single[0], 2)+
Math.pow(single[1], 2));
}
return xScale;
}
/**
* Returns the y-scaling factor of this matrix. This is calculated from the scale and shear.
*
* @return The y-scaling factor.
*/
public float getScalingFactorY()
{
float yScale = single[4];
if( !(Float.compare(single[1], 0.0f) == 0 && Float.compare(single[3], 0.0f) == 0) )
{
yScale = (float)Math.sqrt(Math.pow(single[3], 2)+
Math.pow(single[4], 2));
}
return yScale;
}
/**
* Returns the x-scaling element of this matrix.
*
* @see #getScalingFactorX()
*/
public float getScaleX()
{
return single[0];
}
/**
* Returns the y-shear element of this matrix.
*/
public float getShearY()
{
return single[1];
}
/**
* Returns the x-shear element of this matrix.
*/
public float getShearX()
{
return single[3];
}
/**
* Returns the y-scaling element of this matrix.
*
* @see #getScalingFactorY()
*/
public float getScaleY()
{
return single[4];
}
/**
* Returns the x-translation element of this matrix.
*/
public float getTranslateX()
{
return single[6];
}
/**
* Returns the y-translation element of this matrix.
*/
public float getTranslateY()
{
return single[7];
}
/**
* Get the x position in the matrix. This method is deprecated as it is incorrectly named.
*
* @return The x-position.
* @deprecated Use {@link #getTranslateX} instead
*/
@Deprecated
public float getXPosition()
{
return single[6];
}
/**
* Get the y position. This method is deprecated as it is incorrectly named.
*
* @return The y position.
* @deprecated Use {@link #getTranslateY} instead
*/
@Deprecated
public float getYPosition()
{
return single[7];
}
/**
* Returns a COS array which represent the geometric relevant
* components of the matrix. The last column of the matrix is ignored,
* only the first two columns are returned. This is analog to the
* Matrix(COSArray) constructor.
*/
public COSArray toCOSArray()
{
COSArray array = new COSArray();
array.add(new COSFloat(single[0]));
array.add(new COSFloat(single[1]));
array.add(new COSFloat(single[3]));
array.add(new COSFloat(single[4]));
array.add(new COSFloat(single[6]));
array.add(new COSFloat(single[7]));
return array;
}
@Override
public String toString()
{
return "[" +
single[0] + "," +
single[1] + "," +
single[3] + "," +
single[4] + "," +
single[6] + "," +
single[7] + "]";
}
@Override
public int hashCode()
{
return Arrays.hashCode(single);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
return Arrays.equals(this.single, ((Matrix) obj).single);
}
}
|
pdfbox/src/main/java/org/apache/pdfbox/util/Matrix.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.util;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSFloat;
import org.apache.pdfbox.cos.COSNumber;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.Arrays;
import org.apache.pdfbox.cos.COSBase;
/**
* This class will be used for matrix manipulation.
*
* @author Ben Litchfield
*/
public final class Matrix implements Cloneable
{
static final float[] DEFAULT_SINGLE =
{
1,0,0, // a b 0 sx hy 0 note: hx and hy are reversed vs. the PDF spec as we use
0,1,0, // c d 0 = hx sy 0 AffineTransform's definition x and y shear
0,0,1 // tx ty 1 tx ty 1
};
private final float[] single;
/**
* Constructor. This produces an identity matrix.
*/
public Matrix()
{
single = new float[DEFAULT_SINGLE.length];
System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length);
}
/**
* Creates a matrix from a 6-element (a b c d e f) COS array.
*
* @param array
*/
public Matrix(COSArray array)
{
single = new float[DEFAULT_SINGLE.length];
single[0] = ((COSNumber)array.getObject(0)).floatValue();
single[1] = ((COSNumber)array.getObject(1)).floatValue();
single[3] = ((COSNumber)array.getObject(2)).floatValue();
single[4] = ((COSNumber)array.getObject(3)).floatValue();
single[6] = ((COSNumber)array.getObject(4)).floatValue();
single[7] = ((COSNumber)array.getObject(5)).floatValue();
single[8] = 1;
}
/**
* Creates a transformation matrix with the given 6 elements. Transformation matrices are
* discussed in 8.3.3, "Common Transformations" and 8.3.4, "Transformation Matrices" of the PDF
* specification. For simple purposes (rotate, scale, translate) it is recommended to use the
* static methods below.
*
* @see Matrix#getRotateInstance(double, float, float)
* @see Matrix#getScaleInstance(float, float)
* @see Matrix#getTranslateInstance(float, float)
*
* @param a the X coordinate scaling element (m00) of the 3x3 matrix
* @param b the Y coordinate shearing element (m10) of the 3x3 matrix
* @param c the X coordinate shearing element (m01) of the 3x3 matrix
* @param d the Y coordinate scaling element (m11) of the 3x3 matrix
* @param e the X coordinate translation element (m02) of the 3x3 matrix
* @param f the Y coordinate translation element (m12) of the 3x3 matrix
*/
public Matrix(float a, float b, float c, float d, float e, float f)
{
single = new float[DEFAULT_SINGLE.length];
single[0] = a;
single[1] = b;
single[3] = c;
single[4] = d;
single[6] = e;
single[7] = f;
single[8] = 1;
}
/**
* Creates a matrix with the same elements as the given AffineTransform.
* @param at
*/
public Matrix(AffineTransform at)
{
single = new float[DEFAULT_SINGLE.length];
System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length);
single[0] = (float)at.getScaleX();
single[1] = (float)at.getShearY();
single[3] = (float)at.getShearX();
single[4] = (float)at.getScaleY();
single[6] = (float)at.getTranslateX();
single[7] = (float)at.getTranslateY();
}
/**
* Convenience method to be used when creating a matrix from unverified data. If the parameter
* is a COSArray with at least six numbers, a Matrix object is created from the first six
* numbers and returned. If not, then the identity Matrix is returned.
*
* @param base a COS object, preferably a COSArray with six numbers.
*
* @return a Matrix object.
*/
public static Matrix createMatrix(COSBase base)
{
if (!(base instanceof COSArray))
{
return new Matrix();
}
COSArray array = (COSArray) base;
if (array.size() < 6)
{
return new Matrix();
}
for (int i = 0; i < 6; ++i)
{
if (!(array.getObject(i) instanceof COSNumber))
{
return new Matrix();
}
}
return new Matrix(array);
}
/**
* This method resets the numbers in this Matrix to the original values, which are
* the values that a newly constructed Matrix would have.
*
* @deprecated This method will be removed.
*/
@Deprecated
public void reset()
{
System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length);
}
/**
* Create an affine transform from this matrix's values.
*
* @return An affine transform with this matrix's values.
*/
public AffineTransform createAffineTransform()
{
return new AffineTransform(
single[0], single[1], // m00 m10 = scaleX shearY
single[3], single[4], // m01 m11 = shearX scaleY
single[6], single[7] ); // m02 m12 = tx ty
}
/**
* Set the values of the matrix from the AffineTransform.
*
* @param af The transform to get the values from.
* @deprecated Use the {@link #Matrix(AffineTransform)} constructor instead.
*/
@Deprecated
public void setFromAffineTransform( AffineTransform af )
{
single[0] = (float)af.getScaleX();
single[1] = (float)af.getShearY();
single[3] = (float)af.getShearX();
single[4] = (float)af.getScaleY();
single[6] = (float)af.getTranslateX();
single[7] = (float)af.getTranslateY();
}
/**
* This will get a matrix value at some point.
*
* @param row The row to get the value from.
* @param column The column to get the value from.
*
* @return The value at the row/column position.
*/
public float getValue( int row, int column )
{
return single[row*3+column];
}
/**
* This will set a value at a position.
*
* @param row The row to set the value at.
* @param column the column to set the value at.
* @param value The value to set at the position.
*/
public void setValue( int row, int column, float value )
{
single[row*3+column] = value;
}
/**
* Return a single dimension array of all values in the matrix.
*
* @return The values of this matrix.
*/
public float[][] getValues()
{
float[][] retval = new float[3][3];
retval[0][0] = single[0];
retval[0][1] = single[1];
retval[0][2] = single[2];
retval[1][0] = single[3];
retval[1][1] = single[4];
retval[1][2] = single[5];
retval[2][0] = single[6];
retval[2][1] = single[7];
retval[2][2] = single[8];
return retval;
}
/**
* Return a single dimension array of all values in the matrix.
*
* @return The values ot this matrix.
* @deprecated Use {@link #getValues()} instead.
*/
@Deprecated
public double[][] getValuesAsDouble()
{
double[][] retval = new double[3][3];
retval[0][0] = single[0];
retval[0][1] = single[1];
retval[0][2] = single[2];
retval[1][0] = single[3];
retval[1][1] = single[4];
retval[1][2] = single[5];
retval[2][0] = single[6];
retval[2][1] = single[7];
retval[2][2] = single[8];
return retval;
}
/**
* Concatenates (premultiplies) the given matrix to this matrix.
*
* @param matrix The matrix to concatenate.
*/
public void concatenate(Matrix matrix)
{
matrix.multiply(this, this);
}
/**
* Translates this matrix by the given vector.
*
* @param vector 2D vector
*/
public void translate(Vector vector)
{
Matrix m = Matrix.getTranslateInstance(vector.getX(), vector.getY());
concatenate(m);
}
/**
* Translates this matrix by the given ammount.
*
* @param tx x-translation
* @param ty y-translation
*/
public void translate(float tx, float ty)
{
Matrix m = Matrix.getTranslateInstance(tx, ty);
concatenate(m);
}
/**
* Scales this matrix by the given factors.
*
* @param sx x-scale
* @param sy y-scale
*/
public void scale(float sx, float sy)
{
Matrix m = Matrix.getScaleInstance(sx, sy);
concatenate(m);
}
/**
* Rotares this matrix by the given factors.
*
* @param theta The angle of rotation measured in radians
*/
public void rotate(double theta)
{
Matrix m = Matrix.getRotateInstance(theta, 0, 0);
concatenate(m);
}
/**
* This will take the current matrix and multiply it with a matrix that is passed in.
*
* @param b The matrix to multiply by.
*
* @return The result of the two multiplied matrices.
*/
public Matrix multiply( Matrix b )
{
return this.multiply(b, new Matrix());
}
/**
* This method multiplies this Matrix with the specified other Matrix, storing the product in the specified
* result Matrix. By reusing Matrix instances like this, multiplication chains can be executed without having
* to create many temporary Matrix objects.
* <p>
* It is allowed to have (other == this) or (result == this) or indeed (other == result) but if this is done,
* the backing float[] matrix values may be copied in order to ensure a correct product.
*
* @param other the second operand Matrix in the multiplication
* @param result the Matrix instance into which the result should be stored. If result is null, a new Matrix
* instance is created.
* @return the product of the two matrices.
*/
public Matrix multiply( Matrix other, Matrix result )
{
if (result == null)
{
result = new Matrix();
}
if (other != null && other.single != null)
{
// the operands
float[] thisOperand = this.single;
float[] otherOperand = other.single;
// We're multiplying 2 sets of floats together to produce a third, but we allow
// any of these float[] instances to be the same objects.
// There is the possibility then to overwrite one of the operands with result values
// and therefore corrupt the result.
// If either of these operands are the same float[] instance as the result, then
// they need to be copied.
if (this == result)
{
final float[] thisOrigVals = new float[this.single.length];
System.arraycopy(this.single, 0, thisOrigVals, 0, this.single.length);
thisOperand = thisOrigVals;
}
if (other == result)
{
final float[] otherOrigVals = new float[other.single.length];
System.arraycopy(other.single, 0, otherOrigVals, 0, other.single.length);
otherOperand = otherOrigVals;
}
result.single[0] = thisOperand[0] * otherOperand[0]
+ thisOperand[1] * otherOperand[3]
+ thisOperand[2] * otherOperand[6];
result.single[1] = thisOperand[0] * otherOperand[1]
+ thisOperand[1] * otherOperand[4]
+ thisOperand[2] * otherOperand[7];
result.single[2] = thisOperand[0] * otherOperand[2]
+ thisOperand[1] * otherOperand[5]
+ thisOperand[2] * otherOperand[8];
result.single[3] = thisOperand[3] * otherOperand[0]
+ thisOperand[4] * otherOperand[3]
+ thisOperand[5] * otherOperand[6];
result.single[4] = thisOperand[3] * otherOperand[1]
+ thisOperand[4] * otherOperand[4]
+ thisOperand[5] * otherOperand[7];
result.single[5] = thisOperand[3] * otherOperand[2]
+ thisOperand[4] * otherOperand[5]
+ thisOperand[5] * otherOperand[8];
result.single[6] = thisOperand[6] * otherOperand[0]
+ thisOperand[7] * otherOperand[3]
+ thisOperand[8] * otherOperand[6];
result.single[7] = thisOperand[6] * otherOperand[1]
+ thisOperand[7] * otherOperand[4]
+ thisOperand[8] * otherOperand[7];
result.single[8] = thisOperand[6] * otherOperand[2]
+ thisOperand[7] * otherOperand[5]
+ thisOperand[8] * otherOperand[8];
}
return result;
}
/**
* Transforms the given point by this matrix.
*
* @param point point to transform
*/
public void transform(Point2D point)
{
float x = (float)point.getX();
float y = (float)point.getY();
float a = single[0];
float b = single[1];
float c = single[3];
float d = single[4];
float e = single[6];
float f = single[7];
point.setLocation(x * a + y * c + e, x * b + y * d + f);
}
/**
* Transforms the given point by this matrix.
*
* @param x x-coordinate
* @param y y-coordinate
*/
public Point2D.Float transformPoint(float x, float y)
{
float a = single[0];
float b = single[1];
float c = single[3];
float d = single[4];
float e = single[6];
float f = single[7];
return new Point2D.Float(x * a + y * c + e, x * b + y * d + f);
}
/**
* Transforms the given point by this matrix.
*
* @param vector 2D vector
*/
public Vector transform(Vector vector)
{
float a = single[0];
float b = single[1];
float c = single[3];
float d = single[4];
float e = single[6];
float f = single[7];
float x = vector.getX();
float y = vector.getY();
return new Vector(x * a + y * c + e, x * b + y * d + f);
}
/**
* Create a new matrix with just the scaling operators.
*
* @return A new matrix with just the scaling operators.
* @deprecated This method is due to be removed, please contact us if you make use of it.
*/
@Deprecated
public Matrix extractScaling()
{
Matrix matrix = new Matrix();
matrix.single[0] = this.single[0];
matrix.single[4] = this.single[4];
return matrix;
}
/**
* Convenience method to create a scaled instance.
*
* @param sx The xscale operator.
* @param sy The yscale operator.
* @return A new matrix with just the x/y scaling
*/
public static Matrix getScaleInstance(float sx, float sy)
{
Matrix matrix = new Matrix();
matrix.single[0] = sx;
matrix.single[4] = sy;
return matrix;
}
/**
* Create a new matrix with just the translating operators.
*
* @return A new matrix with just the translating operators.
* @deprecated This method is due to be removed, please contact us if you make use of it.
*/
@Deprecated
public Matrix extractTranslating()
{
Matrix matrix = new Matrix();
matrix.single[6] = this.single[6];
matrix.single[7] = this.single[7];
return matrix;
}
/**
* Convenience method to create a translating instance.
*
* @param tx The x translating operator.
* @param ty The y translating operator.
* @return A new matrix with just the x/y translating.
* @deprecated Use {@link #getTranslateInstance} instead.
*/
@Deprecated
public static Matrix getTranslatingInstance(float tx, float ty)
{
return getTranslateInstance(tx, ty);
}
/**
* Convenience method to create a translating instance.
*
* @param tx The x translating operator.
* @param ty The y translating operator.
* @return A new matrix with just the x/y translating.
*/
public static Matrix getTranslateInstance(float tx, float ty)
{
Matrix matrix = new Matrix();
matrix.single[6] = tx;
matrix.single[7] = ty;
return matrix;
}
/**
* Convenience method to create a rotated instance.
*
* @param theta The angle of rotation measured in radians
* @param tx The x translation.
* @param ty The y translation.
* @return A new matrix with the rotation and the x/y translating.
*/
public static Matrix getRotateInstance(double theta, float tx, float ty)
{
float cosTheta = (float)Math.cos(theta);
float sinTheta = (float)Math.sin(theta);
Matrix matrix = new Matrix();
matrix.single[0] = cosTheta;
matrix.single[1] = sinTheta;
matrix.single[3] = -sinTheta;
matrix.single[4] = cosTheta;
matrix.single[6] = tx;
matrix.single[7] = ty;
return matrix;
}
/**
* Produces a copy of the first matrix, with the second matrix concatenated.
*
* @param a The matrix to copy.
* @param b The matrix to concatenate.
*/
public static Matrix concatenate(Matrix a, Matrix b)
{
Matrix copy = a.clone();
copy.concatenate(b);
return copy;
}
/**
* Clones this object.
* @return cloned matrix as an object.
*/
@Override
public Matrix clone()
{
Matrix clone = new Matrix();
System.arraycopy( single, 0, clone.single, 0, 9 );
return clone;
}
/**
* Returns the x-scaling factor of this matrix. This is calculated from the scale and shear.
*
* @return The x-scaling factor.
*/
public float getScalingFactorX()
{
float xScale = single[0];
/**
* BM: if the trm is rotated, the calculation is a little more complicated
*
* The rotation matrix multiplied with the scaling matrix is:
* ( x 0 0) ( cos sin 0) ( x*cos x*sin 0)
* ( 0 y 0) * (-sin cos 0) = (-y*sin y*cos 0)
* ( 0 0 1) ( 0 0 1) ( 0 0 1)
*
* So, if you want to deduce x from the matrix you take
* M(0,0) = x*cos and M(0,1) = x*sin and use the theorem of Pythagoras
*
* sqrt(M(0,0)^2+M(0,1)^2) =
* sqrt(x2*cos2+x2*sin2) =
* sqrt(x2*(cos2+sin2)) = <- here is the trick cos2+sin2 is one
* sqrt(x2) =
* abs(x)
*/
if( !(Float.compare(single[1], 0.0f) == 0 && Float.compare(single[3], 0.0f) ==0) )
{
xScale = (float)Math.sqrt(Math.pow(single[0], 2)+
Math.pow(single[1], 2));
}
return xScale;
}
/**
* Returns the y-scaling factor of this matrix. This is calculated from the scale and shear.
*
* @return The y-scaling factor.
*/
public float getScalingFactorY()
{
float yScale = single[4];
if( !(Float.compare(single[1], 0.0f) == 0 && Float.compare(single[3], 0.0f) == 0) )
{
yScale = (float)Math.sqrt(Math.pow(single[3], 2)+
Math.pow(single[4], 2));
}
return yScale;
}
/**
* Returns the x-scaling element of this matrix.
*
* @see #getScalingFactorX()
*/
public float getScaleX()
{
return single[0];
}
/**
* Returns the y-shear element of this matrix.
*/
public float getShearY()
{
return single[1];
}
/**
* Returns the x-shear element of this matrix.
*/
public float getShearX()
{
return single[3];
}
/**
* Returns the y-scaling element of this matrix.
*
* @see #getScalingFactorY()
*/
public float getScaleY()
{
return single[4];
}
/**
* Returns the x-translation element of this matrix.
*/
public float getTranslateX()
{
return single[6];
}
/**
* Returns the y-translation element of this matrix.
*/
public float getTranslateY()
{
return single[7];
}
/**
* Get the x position in the matrix. This method is deprecated as it is incorrectly named.
*
* @return The x-position.
* @deprecated Use {@link #getTranslateX} instead
*/
@Deprecated
public float getXPosition()
{
return single[6];
}
/**
* Get the y position. This method is deprecated as it is incorrectly named.
*
* @return The y position.
* @deprecated Use {@link #getTranslateY} instead
*/
@Deprecated
public float getYPosition()
{
return single[7];
}
/**
* Returns a COS array which represents this matrix.
*/
public COSArray toCOSArray()
{
COSArray array = new COSArray();
array.add(new COSFloat(single[0]));
array.add(new COSFloat(single[1]));
array.add(new COSFloat(single[3]));
array.add(new COSFloat(single[4]));
array.add(new COSFloat(single[6]));
array.add(new COSFloat(single[7]));
return array;
}
@Override
public String toString()
{
return "[" +
single[0] + "," +
single[1] + "," +
single[3] + "," +
single[4] + "," +
single[6] + "," +
single[7] + "]";
}
@Override
public int hashCode()
{
return Arrays.hashCode(single);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
return Arrays.equals(this.single, ((Matrix) obj).single);
}
}
|
PDFBOX-4341: update javadoc about drawbacks of this method, by Emmeran Seehuber
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1868345 13f79535-47bb-0310-9956-ffa450edef68
|
pdfbox/src/main/java/org/apache/pdfbox/util/Matrix.java
|
PDFBOX-4341: update javadoc about drawbacks of this method, by Emmeran Seehuber
|
<ide><path>dfbox/src/main/java/org/apache/pdfbox/util/Matrix.java
<ide> }
<ide>
<ide> /**
<del> * Returns a COS array which represents this matrix.
<add> * Returns a COS array which represent the geometric relevant
<add> * components of the matrix. The last column of the matrix is ignored,
<add> * only the first two columns are returned. This is analog to the
<add> * Matrix(COSArray) constructor.
<ide> */
<ide> public COSArray toCOSArray()
<ide> {
|
|
Java
|
mit
|
59f5dfe4652ef54671a932265a81661a270eaa94
| 0 |
Switch2IT/timeskip-api,Switch2IT/timeskip-api,Switch2IT/timeskip,Switch2IT/timeskip,Switch2IT/timeskip,Switch2IT/timeskip-api
|
package be.ehb.facades;
import be.ehb.entities.projects.ActivityBean;
import be.ehb.entities.users.PaygradeBean;
import be.ehb.entities.users.UserBean;
import be.ehb.factories.ExceptionFactory;
import be.ehb.factories.ResponseFactory;
import be.ehb.model.requests.JWTParseRequest;
import be.ehb.model.requests.NewUserRequest;
import be.ehb.model.requests.UpdateCurrentUserRequest;
import be.ehb.model.requests.UpdateUserRequest;
import be.ehb.model.responses.TokenClaimsResponse;
import be.ehb.model.responses.UserResponse;
import be.ehb.security.ISecurityContext;
import be.ehb.security.JWTConstants;
import be.ehb.security.JWTValidation;
import be.ehb.security.idp.IIdpClient;
import be.ehb.storage.IStorageService;
import org.apache.commons.lang3.StringUtils;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.*;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Guillaume Vandecasteele
* @since 2017
*/
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@Default
public class UserFacade implements IUserFacade, Serializable {
private static final Logger log = LoggerFactory.getLogger(UserFacade.class);
@Inject
private JWTValidation jwtValidation;
@Inject
private IStorageService storage;
@Inject
private ISecurityContext securityContext;
@Inject
private IManagementFacade managementFacade;
@Inject
private IIdpClient idpClient;
@Override
public List<UserResponse> listUsers(String organizationId, String roleId, String userId, String firstName, String lastName, String email) {
return storage.listUsers(organizationId, roleId, userId, firstName, lastName, email).parallelStream().map(ResponseFactory::createUserResponse).collect(Collectors.toList());
}
@Override
public UserBean get(String userId) {
return storage.getUser(userId);
}
@Override
public UserResponse getUser(String userId) {
return ResponseFactory.createUserResponse(storage.getUser(userId));
}
@Override
public TokenClaimsResponse parseJWT(JWTParseRequest jwt) {
TokenClaimsResponse rVal = null;
if (StringUtils.isNotEmpty(jwt.getJwt())) {
try {
JwtClaims claims = jwtValidation
.getUnvalidatedContext(jwt.getJwt()).getJwtClaims();
TokenClaimsResponse user = new TokenClaimsResponse();
user.setUserInfo(claims.getClaimsMap());
rVal = user;
} catch (InvalidJwtException | MalformedClaimException e) {
log.error("Failed to parse JWT: {}", jwt);
e.printStackTrace();
}
}
return rVal;
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void initNewUser(JwtClaims claims) {
log.info("Init new user with attributes:{}", claims);
try {
//create user
UserBean newUser = new UserBean();
newUser.setId(claims.getSubject());
if (claims.hasClaim(JWTConstants.GIVEN_NAME) && claims.hasClaim(JWTConstants.SURNAME)) {
newUser.setFirstName(claims.getStringClaimValue(JWTConstants.GIVEN_NAME));
newUser.setLastName(claims.getStringClaimValue(JWTConstants.SURNAME));
} else {
throw ExceptionFactory.jwtValidationException("Missing claims");
}
if (claims.hasClaim(JWTConstants.EMAIL)) {
newUser.setEmail(claims.getStringClaimValue(JWTConstants.EMAIL));
}
newUser.setAdmin(false);
storage.createUser(newUser);
} catch (MalformedClaimException e) {
log.error("Invalid claims in JWT: {}", e.getMessage());
throw ExceptionFactory.unauthorizedException();
}
}
@Override
public UserResponse getCurrentUser() {
return ResponseFactory.createUserResponse(get(securityContext.getCurrentUser()));
}
@Override
public UserResponse createUser(NewUserRequest request) {
UserBean newUser = new UserBean();
newUser.setAdmin(false);
newUser.setEmail(request.getEmail());
newUser.setFirstName(request.getFirstName());
newUser.setLastName(request.getLastName());
newUser.setDefaultHoursPerDay(request.getDefaultHoursPerDay());
newUser.setWorkdays(request.getWorkDays());
if (request.getPaygradeId() != null) {
newUser.setPaygrade(storage.getPaygrade(request.getPaygradeId()));
}
//Retrieve the activity to check if it exists
if (request.getDefaultActivityId() != null) {
ActivityBean activity = storage.getActivity(request.getDefaultActivityId());
newUser.setDefaultActivity(activity.getId());
activity.getProject().getAssignedUsers().add(newUser);
storage.updateProject(activity.getProject());
}
//Create the user on the IDP and get the ID
newUser = idpClient.createUser(newUser);
storage.createUser(newUser);
String userId = newUser.getId();
//Create the memberships
request.getMemberships().forEach(memReq -> managementFacade.updateOrCreateMembership(userId, memReq.getOrganizationId(), memReq.getRole()));
return ResponseFactory.createUserResponse(newUser);
}
@Override
public UserResponse updateCurrentUser(UpdateCurrentUserRequest request) {
String currentUser = securityContext.getCurrentUser();
boolean changed;
if (StringUtils.isEmpty(currentUser)) {
throw ExceptionFactory.noUserContextException();
}
UserBean cUser = storage.getUser(currentUser);
changed = updateEmailIfChanged(cUser, request.getEmail());
if (StringUtils.isNotEmpty(request.getFirstName()) && !request.getFirstName().equals(cUser.getFirstName())) {
cUser.setFirstName(request.getFirstName());
changed = true;
}
if (StringUtils.isNotEmpty(request.getLastName()) && !request.getLastName().equals(cUser.getLastName())) {
cUser.setFirstName(request.getFirstName());
changed = true;
}
if (changed) {
idpClient.updateUser(cUser);
return ResponseFactory.createUserResponse(storage.updateUser(cUser));
} else return null;
}
@Override
public UserResponse updateUser(String userId, UpdateUserRequest request) {
UserBean user = storage.getUser(userId);
boolean changed;
boolean idpChanged;
idpChanged = changed = updateEmailIfChanged(user, request.getEmail());
if (StringUtils.isNotEmpty(request.getFirstName()) && !request.getFirstName().equals(user.getFirstName())) {
user.setFirstName(request.getFirstName());
idpChanged = changed = true;
}
if (StringUtils.isNotEmpty(request.getLastName()) && !request.getLastName().equals(user.getLastName())) {
user.setLastName(request.getLastName());
idpChanged = changed = true;
}
if (request.getPaygradeId() != null && !request.getPaygradeId().equals(user.getPaygrade().getId())) {
PaygradeBean paygrade = storage.getPaygrade(request.getPaygradeId());
user.setPaygrade(paygrade);
changed = true;
}
if (request.getDefaultHoursPerDay() != null && !request.getDefaultHoursPerDay().equals(user.getDefaultHoursPerDay())) {
user.setDefaultHoursPerDay(request.getDefaultHoursPerDay());
changed = true;
}
if (request.getWorkDays() != null && request.getWorkDays().isEmpty() && !new HashSet<>(request.getWorkDays()).equals(new HashSet<>(user.getWorkdays()))) {
user.setWorkdays(request.getWorkDays());
changed = true;
}
if (request.getDefaultActivity() != null && !request.getDefaultActivity().equals(user.getDefaultActivity())) {
ActivityBean activity = storage.getActivity(request.getDefaultActivity());
activity.getProject().getAssignedUsers().add(user);
storage.updateProject(activity.getProject());
user.setDefaultActivity(request.getDefaultActivity());
changed = true;
}
if (changed) {
if (idpChanged) idpClient.updateUser(user);
return ResponseFactory.createUserResponse(storage.updateUser(user));
} else return null;
}
private boolean updateEmailIfChanged(UserBean user, String requestEmail) {
if (StringUtils.isNotEmpty(requestEmail) && !requestEmail.equals(user.getEmail())) {
if (storage.findUserByEmail(requestEmail) != null)
throw ExceptionFactory.userAlreadyExists(requestEmail);
user.setEmail(requestEmail);
return true;
}
return false;
}
}
|
timeskip-ejb/src/main/java/be/ehb/facades/UserFacade.java
|
package be.ehb.facades;
import be.ehb.entities.users.PaygradeBean;
import be.ehb.entities.users.UserBean;
import be.ehb.factories.ExceptionFactory;
import be.ehb.factories.ResponseFactory;
import be.ehb.model.requests.JWTParseRequest;
import be.ehb.model.requests.NewUserRequest;
import be.ehb.model.requests.UpdateCurrentUserRequest;
import be.ehb.model.requests.UpdateUserRequest;
import be.ehb.model.responses.TokenClaimsResponse;
import be.ehb.model.responses.UserResponse;
import be.ehb.security.ISecurityContext;
import be.ehb.security.JWTConstants;
import be.ehb.security.JWTValidation;
import be.ehb.security.idp.IIdpClient;
import be.ehb.storage.IStorageService;
import org.apache.commons.lang3.StringUtils;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.*;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Guillaume Vandecasteele
* @since 2017
*/
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@Default
public class UserFacade implements IUserFacade, Serializable {
private static final Logger log = LoggerFactory.getLogger(UserFacade.class);
@Inject
private JWTValidation jwtValidation;
@Inject
private IStorageService storage;
@Inject
private ISecurityContext securityContext;
@Inject
private IManagementFacade managementFacade;
@Inject
private IIdpClient idpClient;
@Override
public List<UserResponse> listUsers(String organizationId, String roleId, String userId, String firstName, String lastName, String email) {
return storage.listUsers(organizationId, roleId, userId, firstName, lastName, email).parallelStream().map(ResponseFactory::createUserResponse).collect(Collectors.toList());
}
@Override
public UserBean get(String userId) {
return storage.getUser(userId);
}
@Override
public UserResponse getUser(String userId) {
return ResponseFactory.createUserResponse(storage.getUser(userId));
}
@Override
public TokenClaimsResponse parseJWT(JWTParseRequest jwt) {
TokenClaimsResponse rVal = null;
if (StringUtils.isNotEmpty(jwt.getJwt())) {
try {
JwtClaims claims = jwtValidation
.getUnvalidatedContext(jwt.getJwt()).getJwtClaims();
TokenClaimsResponse user = new TokenClaimsResponse();
user.setUserInfo(claims.getClaimsMap());
rVal = user;
} catch (InvalidJwtException | MalformedClaimException e) {
log.error("Failed to parse JWT: {}", jwt);
e.printStackTrace();
}
}
return rVal;
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void initNewUser(JwtClaims claims) {
log.info("Init new user with attributes:{}", claims);
try {
//create user
UserBean newUser = new UserBean();
newUser.setId(claims.getSubject());
if (claims.hasClaim(JWTConstants.GIVEN_NAME) && claims.hasClaim(JWTConstants.SURNAME)) {
newUser.setFirstName(claims.getStringClaimValue(JWTConstants.GIVEN_NAME));
newUser.setLastName(claims.getStringClaimValue(JWTConstants.SURNAME));
} else {
throw ExceptionFactory.jwtValidationException("Missing claims");
}
if (claims.hasClaim(JWTConstants.EMAIL)) {
newUser.setEmail(claims.getStringClaimValue(JWTConstants.EMAIL));
}
newUser.setAdmin(false);
storage.createUser(newUser);
} catch (MalformedClaimException e) {
log.error("Invalid claims in JWT: {}", e.getMessage());
throw ExceptionFactory.unauthorizedException();
}
}
@Override
public UserResponse getCurrentUser() {
return ResponseFactory.createUserResponse(get(securityContext.getCurrentUser()));
}
@Override
public UserResponse createUser(NewUserRequest request) {
UserBean newUser = new UserBean();
newUser.setAdmin(false);
newUser.setEmail(request.getEmail());
newUser.setFirstName(request.getFirstName());
newUser.setLastName(request.getLastName());
newUser.setDefaultHoursPerDay(request.getDefaultHoursPerDay());
newUser.setWorkdays(request.getWorkDays());
if (request.getPaygradeId() != null) {
newUser.setPaygrade(storage.getPaygrade(request.getPaygradeId()));
}
//Retrieve the activity to check if it exists
if (request.getDefaultActivityId() != null) {
newUser.setDefaultActivity(storage.getActivity(request.getDefaultActivityId()).getId());
}
//Create the user on the IDP and get the ID
newUser = idpClient.createUser(newUser);
storage.createUser(newUser);
String userId = newUser.getId();
//Create the memberships
request.getMemberships().forEach(memReq -> managementFacade.updateOrCreateMembership(userId, memReq.getOrganizationId(), memReq.getRole()));
return ResponseFactory.createUserResponse(newUser);
}
@Override
public UserResponse updateCurrentUser(UpdateCurrentUserRequest request) {
String currentUser = securityContext.getCurrentUser();
boolean changed;
if (StringUtils.isEmpty(currentUser)) {
throw ExceptionFactory.noUserContextException();
}
UserBean cUser = storage.getUser(currentUser);
changed = updateEmailIfChanged(cUser, request.getEmail());
if (StringUtils.isNotEmpty(request.getFirstName()) && !request.getFirstName().equals(cUser.getFirstName())) {
cUser.setFirstName(request.getFirstName());
changed = true;
}
if (StringUtils.isNotEmpty(request.getLastName()) && !request.getLastName().equals(cUser.getLastName())) {
cUser.setFirstName(request.getFirstName());
changed = true;
}
if (changed) {
idpClient.updateUser(cUser);
return ResponseFactory.createUserResponse(storage.updateUser(cUser));
} else return null;
}
@Override
public UserResponse updateUser(String userId, UpdateUserRequest request) {
UserBean user = storage.getUser(userId);
boolean changed;
boolean idpChanged;
idpChanged = changed = updateEmailIfChanged(user, request.getEmail());
if (StringUtils.isNotEmpty(request.getFirstName()) && !request.getFirstName().equals(user.getFirstName())) {
user.setFirstName(request.getFirstName());
idpChanged = changed = true;
}
if (StringUtils.isNotEmpty(request.getLastName()) && !request.getLastName().equals(user.getLastName())) {
user.setLastName(request.getLastName());
idpChanged = changed = true;
}
if (request.getPaygradeId() != null && !request.getPaygradeId().equals(user.getPaygrade().getId())) {
PaygradeBean paygrade = storage.getPaygrade(request.getPaygradeId());
user.setPaygrade(paygrade);
changed = true;
}
if (request.getDefaultHoursPerDay() != null && !request.getDefaultHoursPerDay().equals(user.getDefaultHoursPerDay())) {
user.setDefaultHoursPerDay(request.getDefaultHoursPerDay());
changed = true;
}
if (request.getWorkDays() != null && request.getWorkDays().isEmpty() && !new HashSet<>(request.getWorkDays()).equals(new HashSet<>(user.getWorkdays()))) {
user.setWorkdays(request.getWorkDays());
changed = true;
}
if (request.getDefaultActivity() != null && !request.getDefaultActivity().equals(user.getDefaultActivity())) {
storage.getActivity(request.getDefaultActivity());
user.setDefaultActivity(request.getDefaultActivity());
changed = true;
}
if (changed) {
if (idpChanged) idpClient.updateUser(user);
return ResponseFactory.createUserResponse(storage.updateUser(user));
} else return null;
}
private boolean updateEmailIfChanged(UserBean user, String requestEmail) {
if (StringUtils.isNotEmpty(requestEmail) && !requestEmail.equals(user.getEmail())) {
if (storage.findUserByEmail(requestEmail) != null)
throw ExceptionFactory.userAlreadyExists(requestEmail);
user.setEmail(requestEmail);
return true;
}
return false;
}
}
|
assign user to project when changing the default activity
|
timeskip-ejb/src/main/java/be/ehb/facades/UserFacade.java
|
assign user to project when changing the default activity
|
<ide><path>imeskip-ejb/src/main/java/be/ehb/facades/UserFacade.java
<ide> package be.ehb.facades;
<ide>
<add>import be.ehb.entities.projects.ActivityBean;
<ide> import be.ehb.entities.users.PaygradeBean;
<ide> import be.ehb.entities.users.UserBean;
<ide> import be.ehb.factories.ExceptionFactory;
<ide> }
<ide> //Retrieve the activity to check if it exists
<ide> if (request.getDefaultActivityId() != null) {
<del> newUser.setDefaultActivity(storage.getActivity(request.getDefaultActivityId()).getId());
<add> ActivityBean activity = storage.getActivity(request.getDefaultActivityId());
<add> newUser.setDefaultActivity(activity.getId());
<add> activity.getProject().getAssignedUsers().add(newUser);
<add> storage.updateProject(activity.getProject());
<ide> }
<ide> //Create the user on the IDP and get the ID
<ide> newUser = idpClient.createUser(newUser);
<ide> changed = true;
<ide> }
<ide> if (request.getDefaultActivity() != null && !request.getDefaultActivity().equals(user.getDefaultActivity())) {
<del> storage.getActivity(request.getDefaultActivity());
<add> ActivityBean activity = storage.getActivity(request.getDefaultActivity());
<add> activity.getProject().getAssignedUsers().add(user);
<add> storage.updateProject(activity.getProject());
<ide> user.setDefaultActivity(request.getDefaultActivity());
<ide> changed = true;
<ide> }
|
|
JavaScript
|
mit
|
d00b8cfbb9a3bd98f4dbad1f9d393cbeb81725ae
| 0 |
steven-gardiner/piphone,steven-gardiner/piphone
|
#!/usr/bin/env node
var tts = {};
tts.mods = {};
tts.mods.cp = require('child_process');
tts.procs = {}
//tts.procs.espeak = tts.mods.cp.spawn('espeak', ['-w', '/tmp/utter.wav', '--stdin']);
tts.procs.espeak = tts.mods.cp.spawn('espeak', ['--stdout', '--stdin']);
if (false) {
tts.procs.lame = tts.mods.cp.spawn('lame', ['-', '/tmp/utter.mp3']);
tts.procs.espeak.stdout.pipe(tts.procs.lame.stdin);
tts.procs.espeak.stderr.pipe(process.stderr);
tts.procs.lame.stdout.pipe(process.stderr);
tts.procs.lame.stderr.pipe(process.stderr);
tts.procs.lame.stdout.on('end', function() {
tts.procs.play = tts.mods.cp.spawn('mpg123', ['/tmp/utter.mp3']);
tts.procs.play.on('exit', function() {
process.exit();
});
});
} else {
tts.procs.aplay = tts.mods.cp.spawn('aplay', []);
tts.procs.espeak.stdout.pipe(tts.procs.aplay.stdin);
tts.procs.espeak.stderr.pipe(process.stderr);
tts.procs.aplay.on('exit', function() {
process.exit();
});
}
tts.procs.espeak.stdout.on('_end', function() {
tts.procs.aplay = tts.mods.cp.spawn('aplay', ['/tmp/utter.wav']);
tts.procs.aplay.on('exit', function() {
process.exit();
});
});
//process.stdin.pipe(tts.procs.espeak.stdin);
process.stdin.setEncoding('utf8');
process.argv.slice(2).forEach(function(arg) {
tts.procs.espeak.stdin.write(arg);
tts.procs.espeak.stdin.write("\n");
});
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
//console.error("NONNULL");
tts.procs.espeak.stdin.write(chunk);
} else {
//console.error("NULL");
tts.procs.espeak.stdin.end();
//setTimeout(function() { process.exit(); }, 500);
}
});
process.stdin.on('end', function() {
//tts.procs.espeak.stdin.end();
});
|
tts.js
|
#!/usr/bin/env node
var tts = {};
tts.mods = {};
tts.mods.cp = require('child_process');
tts.procs = {}
//tts.procs.espeak = tts.mods.cp.spawn('espeak', ['-w', '/tmp/utter.wav', '--stdin']);
tts.procs.espeak = tts.mods.cp.spawn('espeak', ['--stdout', '--stdin']);
if (false) {
tts.procs.lame = tts.mods.cp.spawn('lame', ['-', '/tmp/utter.mp3']);
tts.procs.espeak.stdout.pipe(tts.procs.lame.stdin);
tts.procs.espeak.stderr.pipe(process.stderr);
tts.procs.lame.stdout.pipe(process.stderr);
tts.procs.lame.stderr.pipe(process.stderr);
tts.procs.lame.stdout.on('end', function() {
tts.procs.play = tts.mods.cp.spawn('mpg123', ['/tmp/utter.mp3']);
tts.procs.play.on('exit', function() {
process.exit();
});
});
} else {
tts.procs.aplay = tts.mods.cp.spawn('aplay', []);
tts.procs.espeak.stdout.pipe(tts.procs.aplay.stdin);
tts.procs.espeak.stderr.pipe(process.stderr);
}
tts.procs.espeak.stdout.on('_end', function() {
tts.procs.aplay = tts.mods.cp.spawn('aplay', ['/tmp/utter.wav']);
tts.procs.aplay.on('exit', function() {
process.exit();
});
});
//process.stdin.pipe(tts.procs.espeak.stdin);
process.stdin.setEncoding('utf8');
process.argv.slice(2).forEach(function(arg) {
tts.procs.espeak.stdin.write(arg);
tts.procs.espeak.stdin.write("\n");
});
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
//console.error("NONNULL");
tts.procs.espeak.stdin.write(chunk);
} else {
//console.error("NULL");
tts.procs.espeak.stdin.end();
//setTimeout(function() { process.exit(); }, 500);
}
});
process.stdin.on('end', function() {
//tts.procs.espeak.stdin.end();
});
|
to quit
|
tts.js
|
to quit
|
<ide><path>ts.js
<ide>
<ide> tts.procs.espeak.stdout.pipe(tts.procs.aplay.stdin);
<ide> tts.procs.espeak.stderr.pipe(process.stderr);
<add>
<add> tts.procs.aplay.on('exit', function() {
<add> process.exit();
<add> });
<ide> }
<ide>
<ide> tts.procs.espeak.stdout.on('_end', function() {
|
|
Java
|
apache-2.0
|
7dac3bdccea22bd357062d5726b1383647628a6b
| 0 |
oalles/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,Darsstar/framework,Scarlethue/vaadin,sitexa/vaadin,Flamenco/vaadin,shahrzadmn/vaadin,Legioth/vaadin,peterl1084/framework,magi42/vaadin,fireflyc/vaadin,Scarlethue/vaadin,Scarlethue/vaadin,synes/vaadin,Scarlethue/vaadin,magi42/vaadin,mittop/vaadin,shahrzadmn/vaadin,fireflyc/vaadin,kironapublic/vaadin,travisfw/vaadin,bmitc/vaadin,asashour/framework,bmitc/vaadin,oalles/vaadin,carrchang/vaadin,carrchang/vaadin,oalles/vaadin,asashour/framework,shahrzadmn/vaadin,kironapublic/vaadin,synes/vaadin,asashour/framework,asashour/framework,mstahv/framework,cbmeeks/vaadin,mittop/vaadin,shahrzadmn/vaadin,mittop/vaadin,Legioth/vaadin,synes/vaadin,Darsstar/framework,synes/vaadin,jdahlstrom/vaadin.react,udayinfy/vaadin,Peppe/vaadin,udayinfy/vaadin,travisfw/vaadin,carrchang/vaadin,travisfw/vaadin,sitexa/vaadin,bmitc/vaadin,magi42/vaadin,udayinfy/vaadin,Darsstar/framework,Darsstar/framework,Peppe/vaadin,Flamenco/vaadin,Legioth/vaadin,shahrzadmn/vaadin,mittop/vaadin,Peppe/vaadin,fireflyc/vaadin,bmitc/vaadin,mstahv/framework,kironapublic/vaadin,peterl1084/framework,cbmeeks/vaadin,magi42/vaadin,Darsstar/framework,oalles/vaadin,peterl1084/framework,Flamenco/vaadin,peterl1084/framework,udayinfy/vaadin,kironapublic/vaadin,cbmeeks/vaadin,sitexa/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,travisfw/vaadin,mstahv/framework,Flamenco/vaadin,Legioth/vaadin,asashour/framework,mstahv/framework,jdahlstrom/vaadin.react,carrchang/vaadin,synes/vaadin,Scarlethue/vaadin,Peppe/vaadin,sitexa/vaadin,kironapublic/vaadin,Legioth/vaadin,cbmeeks/vaadin,Peppe/vaadin,travisfw/vaadin,sitexa/vaadin,fireflyc/vaadin,fireflyc/vaadin,magi42/vaadin,oalles/vaadin,mstahv/framework,jdahlstrom/vaadin.react
|
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.PopupListener;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.itmill.toolkit.terminal.gwt.client.BrowserInfo;
/**
* In Toolkit UI this Overlay should always be used for all elements that
* temporary float over other components like context menus etc. This is to deal
* stacking order correctly with IWindow objects.
*/
public class IToolkitOverlay extends PopupPanel {
/*
* The z-index value from where all overlays live. This can be overridden in
* any extending class.
*/
protected static int Z_INDEX = 20000;
/*
* Shadow element style. If an extending class wishes to use a different
* style of shadow, it can use setShadowStyle(String) to give the shadow
* element a new style name.
*/
public static final String CLASSNAME_SHADOW = "i-shadow";
/*
* The shadow element for this overlay.
*/
private Element shadow;
/**
* The HTML snippet that is used to render the actual shadow. In consists of
* nine different DIV-elements with the following class names:
*
* <pre>
* .i-shadow[-stylename]
* ----------------------------------------------
* | .top-left | .top | .top-right |
* |---------------|-----------|----------------|
* | | | |
* | .left | .center | .right |
* | | | |
* |---------------|-----------|----------------|
* | .bottom-left | .bottom | .bottom-right |
* ----------------------------------------------
* </pre>
*
* See default theme 'shadow.css' for implementation example.
*/
private static final String SHADOW_HTML = "<div class=\"top-left\"></div><div class=\"top\"></div><div class=\"top-right\"></div><div class=\"left\"></div><div class=\"center\"></div><div class=\"right\"></div><div class=\"bottom-left\"></div><div class=\"bottom\"></div><div class=\"bottom-right\"></div>";
public IToolkitOverlay() {
super();
adjustZIndex();
}
public IToolkitOverlay(boolean autoHide) {
super(autoHide);
adjustZIndex();
}
public IToolkitOverlay(boolean autoHide, boolean modal) {
super(autoHide, modal);
adjustZIndex();
}
public IToolkitOverlay(boolean autoHide, boolean modal, boolean showShadow) {
super(autoHide, modal);
if (showShadow) {
shadow = DOM.createDiv();
shadow.setClassName(CLASSNAME_SHADOW);
shadow.setInnerHTML(SHADOW_HTML);
DOM.setStyleAttribute(shadow, "position", "absolute");
addPopupListener(new PopupListener() {
public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
if (shadow.getParentElement() != null) {
shadow.getParentElement().removeChild(shadow);
}
}
});
}
adjustZIndex();
}
private void adjustZIndex() {
setZIndex(Z_INDEX);
}
/**
* Set the z-index (visual stack position) for this overlay.
*
* @param zIndex
* The new z-index
*/
protected void setZIndex(int zIndex) {
DOM.setStyleAttribute(getElement(), "zIndex", "" + zIndex);
if (shadow != null) {
DOM.setStyleAttribute(shadow, "zIndex", "" + zIndex);
}
if (BrowserInfo.get().isIE6()) {
adjustIE6Frame(getElement(), zIndex - 1);
}
}
/**
* Get the z-index (visual stack position) of this overlay.
*
* @return The z-index for this overlay.
*/
private int getZIndex() {
return Integer.parseInt(DOM.getStyleAttribute(getElement(), "zIndex"));
}
@Override
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (shadow != null) {
updateShadowSizeAndPosition(isAnimationEnabled() ? 0 : 1);
}
}
@Override
public void show() {
super.show();
if (shadow != null) {
if (isAnimationEnabled()) {
ShadowAnimation sa = new ShadowAnimation();
sa.run(200);
} else {
updateShadowSizeAndPosition(1.0);
}
}
if (BrowserInfo.get().isIE6()) {
adjustIE6Frame(getElement(), getZIndex());
}
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (shadow != null) {
shadow.getStyle().setProperty("visibility",
visible ? "visible" : "hidden");
}
}
/*
* Needed to position overlays on top of native SELECT elements in IE6. See
* bug #2004
*/
private native void adjustIE6Frame(Element popup, int zindex)
/*-{
// relies on PopupImplIE6
if(popup.__frame)
popup.__frame.style.zIndex = zindex;
}-*/;
@Override
public void setWidth(String width) {
super.setWidth(width);
if (shadow != null) {
updateShadowSizeAndPosition(1.0);
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
if (shadow != null) {
updateShadowSizeAndPosition(1.0);
}
}
/**
* Sets the shadow style for this overlay. Will override any previous style
* for the shadow. The default style name is defined by CLASSNAME_SHADOW.
* The given style will be prefixed with CLASSNAME_SHADOW.
*
* @param style
* The new style name for the shadow element. Will be prefixed by
* CLASSNAME_SHADOW, e.g. style=='foobar' -> actual style
* name=='i-shadow-foobar'.
*/
protected void setShadowStyle(String style) {
if (shadow != null) {
shadow.setClassName(CLASSNAME_SHADOW + "-" + style);
}
}
/*
* Extending classes should always call this method after they change the
* size of overlay without using normal 'setWidth(String)' and
* 'setHeight(String)' methods (if not calling super.setWidth/Height).
*/
protected void updateShadowSizeAndPosition() {
updateShadowSizeAndPosition(1.0);
}
/**
* Recalculates proper position and dimensions for the shadow element. Can
* be used to animate the shadow, using the 'progress' parameter (used to
* animate the shadow in sync with GWT PopupPanel's default animation
* 'PopupPanel.AnimationType.CENTER').
*
* @param progress
* A value between 0.0 and 1.0, indicating the progress of the
* animation (0=start, 1=end).
*/
private void updateShadowSizeAndPosition(final double progress) {
// Don't do anything if overlay element is not attached
if (!isAttached()) {
return;
}
// Calculate proper z-index
String zIndex = null;
try {
// Odd behaviour with Windows Hosted Mode forces us to use
// this redundant try/catch block (See dev.itmill.com #2011)
zIndex = DOM.getStyleAttribute(getElement(), "zIndex");
} catch (Exception ignore) {
// Ignored, will cause no harm
}
if (zIndex == null) {
zIndex = "" + Z_INDEX;
}
// Calculate position and size
if (BrowserInfo.get().isIE()) {
// Shake IE
getOffsetHeight();
getOffsetWidth();
}
int x = getAbsoluteLeft();
int y = getAbsoluteTop();
/* This is needed for IE7 at least */
// Account for the difference between absolute position and the
// body's positioning context.
x -= Document.get().getBodyOffsetLeft();
y -= Document.get().getBodyOffsetTop();
int width = getOffsetWidth();
int height = getOffsetHeight();
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
// Animate the shadow size
x += (int) (width * (1.0 - progress) / 2.0);
y += (int) (height * (1.0 - progress) / 2.0);
width = (int) (width * progress);
height = (int) (height * progress);
// Opera needs some shaking to get parts of the shadow showing
// properly
// (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// Clear the height of all middle elements
DOM.getChild(shadow, 3).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 4).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 5).getStyle().setProperty("height", "auto");
}
// Update correct values
DOM.setStyleAttribute(shadow, "zIndex", zIndex);
DOM.setStyleAttribute(shadow, "width", width + "px");
DOM.setStyleAttribute(shadow, "height", height + "px");
DOM.setStyleAttribute(shadow, "top", y + "px");
DOM.setStyleAttribute(shadow, "left", x + "px");
DOM.setStyleAttribute(shadow, "display", progress < 0.9 ? "none" : "");
// Opera fix, part 2 (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// We'll fix the height of all the middle elements
DOM.getChild(shadow, 3).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 3).getOffsetHeight());
DOM.getChild(shadow, 4).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 4).getOffsetHeight());
DOM.getChild(shadow, 5).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 5).getOffsetHeight());
}
// Attach to dom if not there already
if (shadow.getParentElement() == null) {
RootPanel.get().getElement().insertBefore(shadow, getElement());
}
}
protected class ShadowAnimation extends Animation {
@Override
protected void onUpdate(double progress) {
if (shadow != null) {
updateShadowSizeAndPosition(progress);
}
}
}
}
|
src/com/itmill/toolkit/terminal/gwt/client/ui/IToolkitOverlay.java
|
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.PopupListener;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.itmill.toolkit.terminal.gwt.client.BrowserInfo;
/**
* In Toolkit UI this Overlay should always be used for all elements that
* temporary float over other components like context menus etc. This is to deal
* stacking order correctly with IWindow objects.
*/
public class IToolkitOverlay extends PopupPanel {
/*
* The z-index value from where all overlays live. This can be overridden in
* any extending class.
*/
protected static int Z_INDEX = 20000;
/*
* Shadow element style. If an extending class wishes to use a different
* style of shadow, it can use setShadowStyle(String) to give the shadow
* element a new style name.
*/
public static final String CLASSNAME_SHADOW = "i-shadow";
/*
* The shadow element for this overlay.
*/
private Element shadow;
/**
* The HTML snippet that is used to render the actual shadow. In consists of
* nine different DIV-elements with the following class names:
*
* <pre>
* .i-shadow[-stylename]
* ----------------------------------------------
* | .top-left | .top | .top-right |
* |---------------|-----------|----------------|
* | | | |
* | .left | .center | .right |
* | | | |
* |---------------|-----------|----------------|
* | .bottom-left | .bottom | .bottom-right |
* ----------------------------------------------
* </pre>
*
* See default theme 'shadow.css' for implementation example.
*/
private static final String SHADOW_HTML = "<div class=\"top-left\"></div><div class=\"top\"></div><div class=\"top-right\"></div><div class=\"left\"></div><div class=\"center\"></div><div class=\"right\"></div><div class=\"bottom-left\"></div><div class=\"bottom\"></div><div class=\"bottom-right\"></div>";
public IToolkitOverlay() {
super();
adjustZIndex();
}
public IToolkitOverlay(boolean autoHide) {
super(autoHide);
adjustZIndex();
}
public IToolkitOverlay(boolean autoHide, boolean modal) {
super(autoHide, modal);
adjustZIndex();
}
public IToolkitOverlay(boolean autoHide, boolean modal, boolean showShadow) {
super(autoHide, modal);
if (showShadow) {
shadow = DOM.createDiv();
shadow.setClassName(CLASSNAME_SHADOW);
shadow.setInnerHTML(SHADOW_HTML);
DOM.setStyleAttribute(shadow, "position", "absolute");
addPopupListener(new PopupListener() {
public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
DOM.removeChild(RootPanel.get().getElement(), shadow);
}
});
}
adjustZIndex();
}
private void adjustZIndex() {
setZIndex(Z_INDEX);
}
/**
* Set the z-index (visual stack position) for this overlay.
*
* @param zIndex
* The new z-index
*/
protected void setZIndex(int zIndex) {
DOM.setStyleAttribute(getElement(), "zIndex", "" + zIndex);
if (shadow != null) {
DOM.setStyleAttribute(shadow, "zIndex", "" + zIndex);
}
if (BrowserInfo.get().isIE6()) {
adjustIE6Frame(getElement(), zIndex - 1);
}
}
/**
* Get the z-index (visual stack position) of this overlay.
*
* @return The z-index for this overlay.
*/
private int getZIndex() {
return Integer.parseInt(DOM.getStyleAttribute(getElement(), "zIndex"));
}
@Override
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (shadow != null) {
updateShadowSizeAndPosition(isAnimationEnabled() ? 0 : 1);
}
}
@Override
public void show() {
super.show();
if (shadow != null) {
if (isAnimationEnabled()) {
ShadowAnimation sa = new ShadowAnimation();
sa.run(200);
} else {
updateShadowSizeAndPosition(1.0);
}
}
if (BrowserInfo.get().isIE6()) {
adjustIE6Frame(getElement(), getZIndex());
}
}
/*
* Needed to position overlays on top of native SELECT elements in IE6. See
* bug #2004
*/
private native void adjustIE6Frame(Element popup, int zindex)
/*-{
// relies on PopupImplIE6
if(popup.__frame)
popup.__frame.style.zIndex = zindex;
}-*/;
@Override
public void setWidth(String width) {
super.setWidth(width);
if (shadow != null) {
updateShadowSizeAndPosition(1.0);
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
if (shadow != null) {
updateShadowSizeAndPosition(1.0);
}
}
/**
* Sets the shadow style for this overlay. Will override any previous style
* for the shadow. The default style name is defined by CLASSNAME_SHADOW.
* The given style will be prefixed with CLASSNAME_SHADOW.
*
* @param style
* The new style name for the shadow element. Will be prefixed by
* CLASSNAME_SHADOW, e.g. style=='foobar' -> actual style
* name=='i-shadow-foobar'.
*/
protected void setShadowStyle(String style) {
if (shadow != null) {
shadow.setClassName(CLASSNAME_SHADOW + "-" + style);
}
}
/*
* Extending classes should always call this method after they change the
* size of overlay without using normal 'setWidth(String)' and
* 'setHeight(String)' methods (if not calling super.setWidth/Height).
*/
protected void updateShadowSizeAndPosition() {
updateShadowSizeAndPosition(1.0);
}
/**
* Recalculates proper position and dimensions for the shadow element. Can
* be used to animate the shadow, using the 'progress' parameter (used to
* animate the shadow in sync with GWT PopupPanel's default animation
* 'PopupPanel.AnimationType.CENTER').
*
* @param progress
* A value between 0.0 and 1.0, indicating the progress of the
* animation (0=start, 1=end).
*/
private void updateShadowSizeAndPosition(double progress) {
// Don't do anything if overlay element is not attached
if (!isAttached() || !isVisible()) {
return;
}
// Calculate proper z-index
String zIndex = null;
try {
// Odd behaviour with Windows Hosted Mode forces us to use this
// redundant try/catch block (See dev.itmill.com #2011)
zIndex = DOM.getStyleAttribute(getElement(), "zIndex");
} catch (Exception ignore) {
// Ignored, will cause no harm
}
if (zIndex == null) {
zIndex = "" + Z_INDEX;
}
// Calculate position and size
if (BrowserInfo.get().isIE()) {
// Shake IE
getOffsetHeight();
getOffsetWidth();
}
int x = getAbsoluteLeft();
int y = getAbsoluteTop();
/* This is needed for IE7 at least */
// Account for the difference between absolute position and the
// body's positioning context.
x -= Document.get().getBodyOffsetLeft();
y -= Document.get().getBodyOffsetTop();
int width = getOffsetWidth();
int height = getOffsetHeight();
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
// Animate the shadow size
x += (int) (width * (1.0 - progress) / 2.0);
y += (int) (height * (1.0 - progress) / 2.0);
width = (int) (width * progress);
height = (int) (height * progress);
// Opera needs some shaking to get parts of the shadow showing properly
// (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// Clear the height of all middle elements
DOM.getChild(shadow, 3).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 4).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 5).getStyle().setProperty("height", "auto");
}
// Update correct values
DOM.setStyleAttribute(shadow, "zIndex", zIndex);
DOM.setStyleAttribute(shadow, "width", width + "px");
DOM.setStyleAttribute(shadow, "height", height + "px");
DOM.setStyleAttribute(shadow, "top", y + "px");
DOM.setStyleAttribute(shadow, "left", x + "px");
DOM.setStyleAttribute(shadow, "display", progress < 0.9 ? "none" : "");
// Opera fix, part 2 (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// We'll fix the height of all the middle elements
DOM.getChild(shadow, 3).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 3).getOffsetHeight());
DOM.getChild(shadow, 4).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 4).getOffsetHeight());
DOM.getChild(shadow, 5).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 5).getOffsetHeight());
}
// Attach to dom if not there already
if (shadow.getParentElement() == null) {
RootPanel.get().getElement().insertBefore(shadow, getElement());
}
}
protected class ShadowAnimation extends Animation {
@Override
protected void onUpdate(double progress) {
if (shadow != null) {
updateShadowSizeAndPosition(progress);
}
}
}
}
|
recatored shadow position handling, avoids regression when updating to GWT 1.6
svn changeset:7553/svn branch:6.0
|
src/com/itmill/toolkit/terminal/gwt/client/ui/IToolkitOverlay.java
|
recatored shadow position handling, avoids regression when updating to GWT 1.6
|
<ide><path>rc/com/itmill/toolkit/terminal/gwt/client/ui/IToolkitOverlay.java
<ide>
<ide> addPopupListener(new PopupListener() {
<ide> public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
<del> DOM.removeChild(RootPanel.get().getElement(), shadow);
<add> if (shadow.getParentElement() != null) {
<add> shadow.getParentElement().removeChild(shadow);
<add> }
<ide> }
<ide> });
<ide> }
<ide> }
<ide> }
<ide>
<add> @Override
<add> public void setVisible(boolean visible) {
<add> super.setVisible(visible);
<add> if (shadow != null) {
<add> shadow.getStyle().setProperty("visibility",
<add> visible ? "visible" : "hidden");
<add> }
<add> }
<add>
<ide> /*
<ide> * Needed to position overlays on top of native SELECT elements in IE6. See
<ide> * bug #2004
<ide> * A value between 0.0 and 1.0, indicating the progress of the
<ide> * animation (0=start, 1=end).
<ide> */
<del> private void updateShadowSizeAndPosition(double progress) {
<add> private void updateShadowSizeAndPosition(final double progress) {
<ide> // Don't do anything if overlay element is not attached
<del> if (!isAttached() || !isVisible()) {
<add> if (!isAttached()) {
<ide> return;
<ide> }
<ide> // Calculate proper z-index
<ide> String zIndex = null;
<ide> try {
<del> // Odd behaviour with Windows Hosted Mode forces us to use this
<del> // redundant try/catch block (See dev.itmill.com #2011)
<add> // Odd behaviour with Windows Hosted Mode forces us to use
<add> // this redundant try/catch block (See dev.itmill.com #2011)
<ide> zIndex = DOM.getStyleAttribute(getElement(), "zIndex");
<ide> } catch (Exception ignore) {
<ide> // Ignored, will cause no harm
<ide> width = (int) (width * progress);
<ide> height = (int) (height * progress);
<ide>
<del> // Opera needs some shaking to get parts of the shadow showing properly
<add> // Opera needs some shaking to get parts of the shadow showing
<add> // properly
<ide> // (ticket #2704)
<ide> if (BrowserInfo.get().isOpera()) {
<ide> // Clear the height of all middle elements
|
|
Java
|
mit
|
b779dbda5549acc101186409e0db652970291aac
| 0 |
PLOS/wombat,PLOS/wombat,PLOS/wombat,PLOS/wombat
|
/*
* Copyright (c) 2017 Public Library of Science
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package org.ambraproject.wombat.controller;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import org.ambraproject.wombat.config.site.RequestMappingContextDictionary;
import org.ambraproject.wombat.config.site.Site;
import org.ambraproject.wombat.config.site.SiteParam;
import org.ambraproject.wombat.config.site.url.Link;
import org.ambraproject.wombat.identity.AssetPointer;
import org.ambraproject.wombat.identity.RequestedDoiVersion;
import org.ambraproject.wombat.service.ArticleResolutionService;
import org.ambraproject.wombat.service.ArticleService;
import org.ambraproject.wombat.service.remote.ContentKey;
import org.ambraproject.wombat.service.remote.CorpusContentApi;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
@Controller
public class ArticleAssetController extends WombatController {
private static final Logger log = LoggerFactory.getLogger(ArticleAssetController.class);
@Autowired
private CorpusContentApi corpusContentApi;
@Autowired
private ArticleResolutionService articleResolutionService;
@Autowired
private ArticleService articleService;
@Autowired
private RequestMappingContextDictionary requestMappingContextDictionary;
static enum AssetUrlStyle {
FIGURE_IMAGE("figureImage", "size", new String[]{"figure", "table", "standaloneStrikingImage"}),
ASSET_FILE("assetFile", "type", new String[]{"article", "supplementaryMaterial", "graphic"});
private final String handlerName;
private final String typeParameterName;
private final ImmutableSet<String> itemTypes;
private AssetUrlStyle(String handlerName, String typeParameterName, String[] itemTypes) {
this.handlerName = Objects.requireNonNull(handlerName);
this.typeParameterName = Objects.requireNonNull(typeParameterName);
this.itemTypes = ImmutableSet.copyOf(itemTypes);
}
private static final ImmutableMap<String, AssetUrlStyle> BY_ITEM_TYPE =
EnumSet.allOf(AssetUrlStyle.class).stream()
.flatMap((AssetUrlStyle s) -> s.itemTypes.stream()
.map((String itemType) -> Maps.immutableEntry(itemType, s)))
.collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
static AssetUrlStyle findByItemType(String itemType) {
AssetUrlStyle style = BY_ITEM_TYPE.get(itemType);
if (style == null) throw new IllegalArgumentException("Unrecognized: " + itemType);
return style;
}
Link buildRedirectLink(RequestMappingContextDictionary rmcd,
Site site, RequestedDoiVersion id,
String fileType, boolean isDownload) {
Link.Factory.PatternBuilder builder = Link.toLocalSite(site).toPattern(rmcd, handlerName);
// It's better to use the RequestedDoiVersion than an AssetPointer because, if the user made a request with
// no revision information, we don't want to permanently redirect to a URL that has a revision number.
builder.addQueryParameter(DoiVersionArgumentResolver.ID_PARAMETER, id.getDoi());
id.getRevisionNumber().ifPresent(revisionNumber ->
builder.addQueryParameter(DoiVersionArgumentResolver.REVISION_PARAMETER, revisionNumber));
id.getIngestionNumber().ifPresent(ingestionNumber ->
builder.addQueryParameter(DoiVersionArgumentResolver.INGESTION_PARAMETER, ingestionNumber));
builder.addQueryParameter(typeParameterName, fileType);
if (isDownload) {
builder.addQueryParameter("download", "");
}
return builder.build();
}
}
private void serve(HttpServletRequest requestFromClient, HttpServletResponse responseToClient,
AssetUrlStyle requestedStyle, Site site, RequestedDoiVersion id,
String fileType, boolean isDownload)
throws IOException {
AssetPointer asset = articleResolutionService.toParentIngestion(id);
Map<String, ?> itemMetadata = articleService.getItemMetadata(asset);
String itemType = (String) itemMetadata.get("itemType");
AssetUrlStyle itemStyle = AssetUrlStyle.findByItemType(itemType);
if (requestedStyle != itemStyle) {
Link redirectLink = itemStyle.buildRedirectLink(requestMappingContextDictionary, site, id, fileType, isDownload);
String location = redirectLink.get(requestFromClient);
log.warn(String.format("Redirecting %s request for %s to <%s>. Bad link?",
requestedStyle, asset.asParameterMap(), location));
redirectTo(responseToClient, location);
return;
}
Map<String, ?> files = (Map<String, ?>) itemMetadata.get("files");
Map<String, ?> fileRepoKey = (Map<String, ?>) files.get(fileType);
if (fileRepoKey == null) {
fileRepoKey = handleUnmatchedFileType(id, itemType, fileType, files);
}
// TODO: Check visibility against site?
ContentKey contentKey = createKey(fileRepoKey);
try (CloseableHttpResponse responseFromApi = corpusContentApi.request(contentKey, ImmutableList.of())) {
forwardAssetResponse(responseFromApi, responseToClient, isDownload);
}
}
/**
* The keys are item types where, if at item of that type has only one file and get a request for an missing file
* type, we prefer to serve the one file and log a warning rather than serve a 404 response. The values are file types
* expected to exist, to ensure that we still serve 404s on URLs that are total nonsense.
* <p>
* This is a kludge over a data condition in PLOS's corpus where some items were not ingested with reformatted images
* as expected. We assume that it is safe to recover gracefully for certain item types because there is generally
* little difference in image resizing.
* <p>
* The main omission is {@code itemType="supplementaryMaterial"}, where we still want to be strict about the {@code
* fileType="supplementary"}. Also, a hit on {@code itemType="figure"} or {@code itemType="table"} is bigger trouble
* because the image resizing can be very significant, so we want a hard failure in that case.
*/
// TODO: Get values from a Rhino API library, if and when such a thing exists
private static final ImmutableSetMultimap<String, String> ITEM_TYPES_TO_TOLERATE = ImmutableSetMultimap.<String, String>builder()
.putAll("graphic", "original", "thumbnail")
.putAll("standaloneStrikingImage", "original", "small", "inline", "medium", "large")
.build();
/**
* Handle a file request where the supplied file type could not be matched to any files for an existing item. If
* possible, resolve to another file to serve instead. Else, throw an appropriate exception.
*/
private static Map<String, ?> handleUnmatchedFileType(RequestedDoiVersion id,
String itemType, String fileType,
Map<String, ?> files) {
if (files.size() == 1 && ITEM_TYPES_TO_TOLERATE.containsEntry(itemType, fileType)) {
Map.Entry<String, ?> onlyEntry = Iterables.getOnlyElement(files.entrySet());
log.warn(String.format("On %s (%s), received request for %s; only available file is %s",
id, itemType, fileType, onlyEntry.getKey()));
return (Map<String, ?>) onlyEntry.getValue();
}
String message = String.format("Unrecognized file type (\"%s\") for id: %s", fileType, id);
throw new NotFoundException(message);
}
/**
* Redirect to a given link. (We can't just return a {@link org.springframework.web.servlet.view.RedirectView} because
* we ordinarily want to pass the raw response to {@link #forwardAssetResponse}. So we mess around with it directly.)
*/
private void redirectTo(HttpServletResponse response, String location) {
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader(HttpHeaders.LOCATION, location);
}
@RequestMapping(name = "assetFile", value = "/article/file", params = {"type"})
public void serveAssetFile(HttpServletRequest request, HttpServletResponse response,
@SiteParam Site site,
RequestedDoiVersion id,
@RequestParam(value = "type", required = true) String fileType,
@RequestParam(value = "download", required = false) String isDownload)
throws IOException {
serve(request, response, AssetUrlStyle.ASSET_FILE, site, id, fileType, booleanParameter(isDownload));
}
@RequestMapping(name = "figureImage", value = "/article/figure/image")
public void serveFigureImage(HttpServletRequest request, HttpServletResponse response,
@SiteParam Site site,
RequestedDoiVersion id,
@RequestParam(value = "size", required = true) String figureSize,
@RequestParam(value = "download", required = false) String isDownload)
throws IOException {
serve(request, response, AssetUrlStyle.FIGURE_IMAGE, site, id, figureSize, booleanParameter(isDownload));
}
private static ContentKey createKey(Map<String, ?> fileRepoKey) {
String key = (String) fileRepoKey.get("crepoKey");
UUID uuid = UUID.fromString((String) fileRepoKey.get("crepoUuid"));
ContentKey contentKey = ContentKey.createForUuid(key, uuid);
if (fileRepoKey.get("bucketName") != null) {
contentKey.setBucketName(fileRepoKey.get("bucketName").toString());
}
return contentKey;
}
}
|
src/main/java/org/ambraproject/wombat/controller/ArticleAssetController.java
|
/*
* Copyright (c) 2017 Public Library of Science
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package org.ambraproject.wombat.controller;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import org.ambraproject.wombat.config.site.RequestMappingContextDictionary;
import org.ambraproject.wombat.config.site.Site;
import org.ambraproject.wombat.config.site.SiteParam;
import org.ambraproject.wombat.config.site.url.Link;
import org.ambraproject.wombat.identity.AssetPointer;
import org.ambraproject.wombat.identity.RequestedDoiVersion;
import org.ambraproject.wombat.service.ArticleResolutionService;
import org.ambraproject.wombat.service.ArticleService;
import org.ambraproject.wombat.service.remote.ContentKey;
import org.ambraproject.wombat.service.remote.CorpusContentApi;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
@Controller
public class ArticleAssetController extends WombatController {
private static final Logger log = LoggerFactory.getLogger(ArticleAssetController.class);
@Autowired
private CorpusContentApi corpusContentApi;
@Autowired
private ArticleResolutionService articleResolutionService;
@Autowired
private ArticleService articleService;
@Autowired
private RequestMappingContextDictionary requestMappingContextDictionary;
static enum AssetUrlStyle {
FIGURE_IMAGE("figureImage", "size", new String[]{"figure", "table", "standaloneStrikingImage"}),
ASSET_FILE("assetFile", "type", new String[]{"article", "supplementaryMaterial", "graphic"});
private final String handlerName;
private final String typeParameterName;
private final ImmutableSet<String> itemTypes;
private AssetUrlStyle(String handlerName, String typeParameterName, String[] itemTypes) {
this.handlerName = Objects.requireNonNull(handlerName);
this.typeParameterName = Objects.requireNonNull(typeParameterName);
this.itemTypes = ImmutableSet.copyOf(itemTypes);
}
private static final ImmutableMap<String, AssetUrlStyle> BY_ITEM_TYPE =
EnumSet.allOf(AssetUrlStyle.class).stream()
.flatMap((AssetUrlStyle s) -> s.itemTypes.stream()
.map((String itemType) -> Maps.immutableEntry(itemType, s)))
.collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
static AssetUrlStyle findByItemType(String itemType) {
AssetUrlStyle style = BY_ITEM_TYPE.get(itemType);
if (style == null) throw new IllegalArgumentException("Unrecognized: " + itemType);
return style;
}
Link buildRedirectLink(RequestMappingContextDictionary rmcd,
Site site, RequestedDoiVersion id,
String fileType, boolean isDownload) {
Link.Factory.PatternBuilder builder = Link.toLocalSite(site).toPattern(rmcd, handlerName);
// It's better to use the RequestedDoiVersion than an AssetPointer because, if the user made a request with
// no revision information, we don't want to permanently redirect to a URL that has a revision number.
builder.addQueryParameter(DoiVersionArgumentResolver.ID_PARAMETER, id.getDoi());
id.getRevisionNumber().ifPresent(revisionNumber ->
builder.addQueryParameter(DoiVersionArgumentResolver.REVISION_PARAMETER, revisionNumber));
id.getIngestionNumber().ifPresent(ingestionNumber ->
builder.addQueryParameter(DoiVersionArgumentResolver.INGESTION_PARAMETER, ingestionNumber));
builder.addQueryParameter(typeParameterName, fileType);
if (isDownload) {
builder.addQueryParameter("download", "");
}
return builder.build();
}
}
private void serve(HttpServletRequest requestFromClient, HttpServletResponse responseToClient,
AssetUrlStyle requestedStyle, Site site, RequestedDoiVersion id,
String fileType, boolean isDownload)
throws IOException {
AssetPointer asset = articleResolutionService.toParentIngestion(id);
Map<String, ?> itemMetadata = articleService.getItemMetadata(asset);
String itemType = (String) itemMetadata.get("itemType");
AssetUrlStyle itemStyle = AssetUrlStyle.findByItemType(itemType);
if (requestedStyle != itemStyle) {
Link redirectLink = itemStyle.buildRedirectLink(requestMappingContextDictionary, site, id, fileType, isDownload);
String location = redirectLink.get(requestFromClient);
log.warn(String.format("Redirecting %s request for %s to <%s>. Bad link?",
requestedStyle, asset.asParameterMap(), location));
redirectTo(responseToClient, location);
return;
}
Map<String, ?> files = (Map<String, ?>) itemMetadata.get("files");
Map<String, ?> fileRepoKey = (Map<String, ?>) files.get(fileType);
if (fileRepoKey == null) {
fileRepoKey = handleUnmatchedFileType(id, itemType, fileType, files);
}
// TODO: Check visibility against site?
ContentKey contentKey = createKey(fileRepoKey);
try (CloseableHttpResponse responseFromApi = corpusContentApi.request(contentKey, ImmutableList.of())) {
forwardAssetResponse(responseFromApi, responseToClient, isDownload);
}
}
/**
* The keys are item types where, if at item of that type has only one file and get a request for an missing file
* type, we prefer to serve the one file and log a warning rather than serve a 404 response. The values are file types
* expected to exist, to ensure that we still serve 404s on URLs that are total nonsense.
* <p>
* This is a kludge over a data condition in PLOS's corpus where some items were not ingested with reformatted images
* as expected. We assume that it is safe to recover gracefully for certain item types because there is generally
* little difference in image resizing.
* <p>
* The main omission is {@code itemType="supplementaryMaterial"}, where we still want to be strict about the {@code
* fileType="supplementary"}. Also, a hit on {@code itemType="figure"} or {@code itemType="table"} is bigger trouble
* because the image resizing can be very significant, so we want a hard failure in that case.
*/
// TODO: Get values from a Rhino API library, if and when such a thing exists
private static final ImmutableSetMultimap<String, String> ITEM_TYPES_TO_TOLERATE = ImmutableSetMultimap.<String, String>builder()
.putAll("graphic", "original", "thumbnail")
.putAll("standaloneStrikingImage", "original", "small", "inline", "medium", "large")
.build();
/**
* Handle a file request where the supplied file type could not be matched to any files for an existing item. If
* possible, resolve to another file to serve instead. Else, throw an appropriate exception.
*/
private static Map<String, ?> handleUnmatchedFileType(RequestedDoiVersion id,
String itemType, String fileType,
Map<String, ?> files) {
if (files.size() == 1 && ITEM_TYPES_TO_TOLERATE.containsEntry(itemType, fileType)) {
Map.Entry<String, ?> onlyEntry = Iterables.getOnlyElement(files.entrySet());
log.warn(String.format("On %s (%s), received request for %s; only available file is %s",
id, itemType, fileType, onlyEntry.getKey()));
return (Map<String, ?>) onlyEntry.getValue();
}
String message = String.format("Unrecognized file type (\"%s\") for id: %s", fileType, id);
throw new NotFoundException(message);
}
/**
* Redirect to a given link. (We can't just return a {@link org.springframework.web.servlet.view.RedirectView} because
* we ordinarily want to pass the raw response to {@link #forwardAssetResponse}. So we mess around with it directly.)
*/
private void redirectTo(HttpServletResponse response, String location) {
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader(HttpHeaders.LOCATION, location);
}
@RequestMapping(name = "assetFile", value = "/article/file", params = {"type"})
public void serveAssetFile(HttpServletRequest request, HttpServletResponse response,
@SiteParam Site site,
RequestedDoiVersion id,
@RequestParam(value = "type", required = true) String fileType,
@RequestParam(value = "download", required = false) String isDownload)
throws IOException {
serve(request, response, AssetUrlStyle.ASSET_FILE, site, id, fileType, booleanParameter(isDownload));
}
@RequestMapping(name = "figureImage", value = "/article/figure/image")
public void serveFigureImage(HttpServletRequest request, HttpServletResponse response,
@SiteParam Site site,
RequestedDoiVersion id,
@RequestParam(value = "size", required = true) String figureSize,
@RequestParam(value = "download", required = false) String isDownload)
throws IOException {
serve(request, response, AssetUrlStyle.FIGURE_IMAGE, site, id, figureSize, booleanParameter(isDownload));
}
private static ContentKey createKey(Map<String, ?> fileRepoKey) {
// TODO: Account for bucket name
String key = (String) fileRepoKey.get("crepoKey");
UUID uuid = UUID.fromString((String) fileRepoKey.get("crepoUuid"));
return ContentKey.createForUuid(key, uuid);
}
}
|
RARO-125: tie pdf and xml downloads to bucket name
|
src/main/java/org/ambraproject/wombat/controller/ArticleAssetController.java
|
RARO-125: tie pdf and xml downloads to bucket name
|
<ide><path>rc/main/java/org/ambraproject/wombat/controller/ArticleAssetController.java
<ide> }
<ide>
<ide> private static ContentKey createKey(Map<String, ?> fileRepoKey) {
<del> // TODO: Account for bucket name
<ide> String key = (String) fileRepoKey.get("crepoKey");
<ide> UUID uuid = UUID.fromString((String) fileRepoKey.get("crepoUuid"));
<del> return ContentKey.createForUuid(key, uuid);
<add> ContentKey contentKey = ContentKey.createForUuid(key, uuid);
<add> if (fileRepoKey.get("bucketName") != null) {
<add> contentKey.setBucketName(fileRepoKey.get("bucketName").toString());
<add> }
<add> return contentKey;
<ide> }
<ide>
<ide> }
|
|
Java
|
lgpl-2.1
|
0cdd88e2dfa3a083dfbfc90788d0146c11bab0cc
| 0 |
vigna/Sux4J,vigna/Sux4J,vigna/Sux4J,vigna/Sux4J
|
/*
* Sux4J: Succinct data structures for Java
*
* Copyright (C) 2020 Sebastiano Vigna
*
* 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 3 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
package it.unimi.dsi.sux4j.util;
import static it.unimi.dsi.bits.LongArrayBitVector.bit;
import static it.unimi.dsi.bits.LongArrayBitVector.bits;
import static it.unimi.dsi.bits.LongArrayBitVector.word;
import java.io.Serializable;
import it.unimi.dsi.fastutil.bytes.ByteIterable;
import it.unimi.dsi.fastutil.bytes.ByteIterator;
import it.unimi.dsi.fastutil.ints.IntIterable;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.longs.LongIterable;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.shorts.ShortIterable;
import it.unimi.dsi.fastutil.shorts.ShortIterator;
import it.unimi.dsi.sux4j.bits.SimpleSelect;
import it.unimi.dsi.sux4j.bits.SimpleSelectZero;
/**
* An extension of {@link EliasFanoMonotoneLongBigList} providing indexing (i.e., content-based
* addressing).
*
* <p>
* This implementation uses a {@link SimpleSelectZero} structure to support zero-selection inside
* the upper-bits array, which makes it possible to implement fast content-addressed based access
* methods such as {@link #predecessor(long)}, {@link #weakPredecessor(long)},
* {@link #successor(long)}, {@link #strictSuccessor(long)}, {@link #contains(long)} and
* {@link #indexOf(long)}.
*
* <p>
* This class is thread safe as long as you do not use {@link #index()}, as its value depend on an
* interval variable that caches the result of {@link #predecessor(long)},
* {@link #weakPredecessor(long)}, {@link #successor(long)}, and {@link #strictSuccessor(long)}.
* Usually it is possible to work around the issue using the alternative methods
* {@link #predecessorIndex(long)}, {@link #weakPredecessorIndex(long)},
* {@link #successorIndex(long)}, and {@link #strictSuccessorIndex(long)}.
*/
public class EliasFanoIndexedMonotoneLongBigList extends EliasFanoMonotoneLongBigList implements Serializable {
private static final long serialVersionUID = 0L;
/** The select structure used to extract the upper bits. */
protected final SimpleSelectZero selectUpperZero = new SimpleSelectZero(selectUpper.bitVector());
/** The upper bits as a long array. */
protected final long[] upperBits = selectUpper.bitVector().bits();
/**
* The index of the value returned by {@link #predecessor(long)}, {@link #weakPredecessor(long)},
* {@link #successor(long)}, and {@link #strictSuccessor(long)}.
*/
private long currentIndex = -1;
/** The last element of the sequence, or -1 if the sequence is empty. */
private final long lastElement = isEmpty() ? -1 : getLong(size64() - 1);
/** The first element of the sequence, or {@link Long#MAX_VALUE} if the sequence is empty. */
private final long firstElement = isEmpty() ? Long.MAX_VALUE : getLong(0);
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final ByteIterable list) {
super(list);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final IntIterable list) {
super(list);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long length, final int l, final long[] lowerBits, final SimpleSelect selectUpper) {
super(length, l, lowerBits, selectUpper);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final ByteIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final IntIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final LongIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final ShortIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long[] a, final LongIterator iterator) {
super(a, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final LongIterable list) {
super(list);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final ShortIterable list) {
super(list);
}
/**
* Returns the first element of the sequence that is greater than or equal to the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the first value of the sequence that is greater than or equal to {@code lowerBound}, or
* {@link Long#MAX_VALUE} if no such value exists.
* @see #strictSuccessor(long)
*/
public long successor(final long lowerBound) {
if (lowerBound <= firstElement) {
currentIndex = 0;
return firstElement;
}
if (lowerBound > lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
final long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
long rank = zeroesToSkip == 0 ? 0 : position - zeroesToSkip + 1;
if (l == 0) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
currentIndex = rank;
return upperBits;
} else {
long lowerBitsOffset = rank * l;
final int m = Long.SIZE - l;
for (;;) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
final long lower = lowerBits[startWord] >>> startBit;
final long v = upperBits << l | (startBit <= m ? lower : lower | lowerBits[startWord + 1] << -startBit) & lowerBitsMask;
if (v >= lowerBound) {
currentIndex = rank;
return v;
}
window &= window - 1;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the index of first element of the sequence that is greater than or equal to the provided
* bound.
*
* <p>
* This method is significantly faster than {@link #successor(long)}, as it does not have to compute
* the actual successor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the index of the first value of the sequence that is greater than or equal to
* {@code lowerBound}, or {@link Long#MAX_VALUE} if no such value exists.
* @see #successor(long)
*/
public long successorIndex(final long lowerBound) {
if (lowerBound <= firstElement) return 0;
if (lowerBound > lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1) + 1;
long rank = position - zeroesToSkip;
if (l == 0) return rank;
else {
long lowerBitsOffset = rank * l;
final long lowerBoundLowerBits = lowerBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
long lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower >= lowerBoundLowerBits) return rank;
position++;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the first element of the sequence that is greater than the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the first value of the sequence that is greater than {@code lowerBound}, or
* {@link Long#MAX_VALUE} if no such value exists.
* @see #successor(long)
*/
public long strictSuccessor(final long lowerBound) {
if (lowerBound < firstElement) {
currentIndex = 0;
return firstElement;
}
if (lowerBound >= lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
if (l == 0) {
final long position = selectUpperZero.selectZero(zeroesToSkip);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
final long rank = position - zeroesToSkip;
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
currentIndex = rank;
return upperBits;
} else {
final long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
long rank = zeroesToSkip == 0 ? 0 : position - zeroesToSkip + 1;
long lowerBitsOffset = rank * l;
final int m = Long.SIZE - l;
for (;;) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
final long lower = lowerBits[startWord] >>> startBit;
final long v = upperBits << l | (startBit <= m ? lower : lower | lowerBits[startWord + 1] << -startBit) & lowerBitsMask;
if (v > lowerBound) {
currentIndex = rank;
return v;
}
window &= window - 1;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the index of first element of the sequence that is greater than the provided bound.
*
* <p>
* This method is significantly faster than {@link #strictSuccessor(long)}, as it does not have to
* compute the actual strict successor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the index of the first value of the sequence that is greater than {@code lowerBound}, or
* {@link Long#MAX_VALUE} if no such value exists.
* @see #strictSuccessor(long)
*/
public long strictSuccessorIndex(final long lowerBound) {
if (lowerBound < firstElement) return 0;
if (lowerBound >= lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
if (l == 0) {
final long position = selectUpperZero.selectZero(zeroesToSkip);
return position - zeroesToSkip;
} else {
long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1) + 1;
long rank = position - zeroesToSkip;
long lowerBitsOffset = rank * l;
final long lowerBoundLowerBits = lowerBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
long lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower > lowerBoundLowerBits) return rank;
position++;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the last value of the sequence that is less than the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param upperBound a strict upper bound on the returned value.
* @return the last value of the sequence that is less than {@code upperBound}, or
* {@link Long#MIN_VALUE} if no such value exists.
* @see #weakPredecessor(long)
*/
public long predecessor(final long upperBound) {
if (upperBound <= firstElement) return Long.MIN_VALUE;
if (upperBound > lastElement) {
currentIndex = length - 1;
return lastElement;
}
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) {
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) break;
position--;
rank--;
}
currentIndex = rank;
return selectUpper.select(rank) - rank;
} else {
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if ((upperBits[word(position)] & 1L << position) == 0) {
int zeros = (int)(position | -Long.SIZE); // == - (Long.SIZE - (position % Long.SIZE))
int curr = word(position);
long window = upperBits[curr] & ~(-1L << position);
while (window == 0) {
window = upperBits[--curr];
zeros += Long.SIZE;
}
currentIndex = rank;
return position - zeros - Long.numberOfLeadingZeros(window) - rank - 1 << l | lower;
}
if (lower < upperBoundLowerBits) {
currentIndex = rank;
return position - rank << l | lower;
}
lowerBitsOffset -= l;
position--;
rank--;
}
}
}
/**
* Returns the index of the last value of the sequence that is less than the provided bound.
*
* <p>
* This method is significantly faster than {@link #predecessor(long)}, as it does not have to
* compute the actual predecessor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param upperBound an upper bound on the returned value.
* @return the index of the last value of the sequence that is less than {@code upperBound}, or
* {@link Long#MIN_VALUE} if no such value exists.
* @see #predecessor(long)
*/
public long predecessorIndex(final long upperBound) {
if (upperBound <= firstElement) return Long.MIN_VALUE;
if (upperBound > lastElement) return length - 1;
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) {
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
position--;
rank--;
}
} else {
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower < upperBoundLowerBits) return rank;
rank--;
position--;
lowerBitsOffset -= l;
}
}
}
/**
* Returns the last value of the sequence that is less than or equal to the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param upperBound an upper bound on the returned value.
* @return the last value of the sequence that is less than or equal to {@code upperBound}, or
* {@link Long#MIN_VALUE} if no such value exists.
* @see #predecessor(long)
*/
public long weakPredecessor(final long upperBound) {
if (upperBound < firstElement) return Long.MIN_VALUE;
if (upperBound >= lastElement) {
currentIndex = length - 1;
return lastElement;
}
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) {
currentIndex = rank;
return selectUpper.select(rank) - rank;
} else {
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if ((upperBits[word(position)] & 1L << position) == 0) {
int zeros = (int)(position | -Long.SIZE); // == - (Long.SIZE - (position % Long.SIZE))
int curr = word(position);
long window = upperBits[curr] & ~(-1L << position);
while (window == 0) {
window = upperBits[--curr];
zeros += Long.SIZE;
}
currentIndex = rank;
return position - zeros - Long.numberOfLeadingZeros(window) - rank - 1 << l | lower;
}
if (lower <= upperBoundLowerBits) {
currentIndex = rank;
return position - rank << l | lower;
}
rank--;
lowerBitsOffset -= l;
position--;
}
}
}
/**
* Returns the index of the last value of the sequence that is less than or equal to the provided
* bound.
*
* <p>
* This method is significantly faster than {@link #weakPredecessor(long)}, as it does not have to
* compute the actual weak predecessor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param upperBound an upper bound on the returned value.
* @return the index of the last value of the sequence that is less than or equal to
* {@code upperBound}, or {@link Long#MIN_VALUE} if no such value exists.
* @see #weakPredecessor(long)
*/
public long weakPredecessorIndex(final long upperBound) {
if (upperBound < firstElement) return Long.MIN_VALUE;
if (upperBound >= lastElement) return length - 1;
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) return rank;
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower <= upperBoundLowerBits) return rank;
rank--;
position--;
lowerBitsOffset -= l;
}
}
/**
* Returns the index of the first occurrence of the specified element in the sequence, or -1 if the
* element does not belong to the sequence.
*
* <p>
* This method does not change the value returned by {@link #index()}.
*
* @param x a long.
*/
@Override
public long indexOf(final long x) {
if (x < firstElement || x > lastElement) return -1;
final long zeroesToSkip = x >>> l;
final long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
long rank = zeroesToSkip == 0 ? 0 : position - zeroesToSkip + 1;
if (l == 0) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
return upperBits == x ? rank : -1;
} else {
long lowerBitsOffset = rank * l;
final int m = Long.SIZE - l;
for (;;) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
final long lower = lowerBits[startWord] >>> startBit;
final long v = upperBits << l | (startBit <= m ? lower : lower | lowerBits[startWord + 1] << -startBit) & lowerBitsMask;
if (v >= x) return v == x ? rank : -1;
window &= window - 1;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns true if the sequence contains the specified element.
*
* <p>
* This method does not change the value returned by {@link #index()}. Use {@link #indexOf(long)} if
* you need to retrieve the position of an element.
*
* @param x a long.
* @return true if the sequence contains {@code x}.
*/
@Override
public boolean contains(final long x) {
return indexOf(x) != -1;
}
/**
* Returns the index realizing the last value returned by {@link #predecessor(long)},
* {@link #weakPredecessor(long)}, {@link #successor(long)}, and {@link #strictSuccessor(long)}.
*
* <p>
* Usage of this method makes instances of this class not thread safe, as the return value is cached
* internally.
*
* @return the index of the element realizing the last value returned by {@link #predecessor(long)},
* {@link #weakPredecessor(long)}, {@link #successor(long)}, and
* {@link #strictSuccessor(long)}, or -1 if no such method has ever been called.
*/
public long index() {
return currentIndex;
}
}
|
src/it/unimi/dsi/sux4j/util/EliasFanoIndexedMonotoneLongBigList.java
|
/*
* Sux4J: Succinct data structures for Java
*
* Copyright (C) 2020 Sebastiano Vigna
*
* 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 3 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
package it.unimi.dsi.sux4j.util;
import static it.unimi.dsi.bits.LongArrayBitVector.bit;
import static it.unimi.dsi.bits.LongArrayBitVector.bits;
import static it.unimi.dsi.bits.LongArrayBitVector.word;
import java.io.Serializable;
import it.unimi.dsi.fastutil.bytes.ByteIterable;
import it.unimi.dsi.fastutil.bytes.ByteIterator;
import it.unimi.dsi.fastutil.ints.IntIterable;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.longs.LongIterable;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.shorts.ShortIterable;
import it.unimi.dsi.fastutil.shorts.ShortIterator;
import it.unimi.dsi.sux4j.bits.SimpleSelect;
import it.unimi.dsi.sux4j.bits.SimpleSelectZero;
/**
* An extension of {@link EliasFanoMonotoneLongBigList} providing indexing (i.e., content-based
* addressing).
*
* <p>
* This implementation uses a {@link SimpleSelectZero} structure to support zero-selection inside
* the upper-bits array, which makes it possible to implement fast content-addressed based access
* methods such as {@link #predecessor(long)}, {@link #weakPredecessor(long)},
* {@link #successor(long)}, {@link #strictSuccessor(long)}, {@link #contains(long)} and
* {@link #indexOf(long)}.
*
* <p>
* This class is thread safe as long as you do not use {@link #index()}, as its value depend on an
* interval variable that caches the result of {@link #predecessor(long)},
* {@link #weakPredecessor(long)}, {@link #successor(long)}, and {@link #strictSuccessor(long)}.
* Usually it is possible to work around the issue using the alternative methods
* {@link #predecessorIndex(long)}, {@link #weakPredecessorIndex(long)},
* {@link #successorIndex(long)}, and {@link #strictSuccessorIndex(long)}.
*/
public class EliasFanoIndexedMonotoneLongBigList extends EliasFanoMonotoneLongBigList implements Serializable {
private static final long serialVersionUID = 0L;
/** The select structure used to extract the upper bits. */
protected final SimpleSelectZero selectUpperZero = new SimpleSelectZero(selectUpper.bitVector());
/** The upper bits as a long array. */
protected final long[] upperBits = selectUpper.bitVector().bits();
/**
* The index of the value returned by {@link #predecessor(long)}, {@link #weakPredecessor(long)},
* {@link #successor(long)}, and {@link #strictSuccessor(long)}.
*/
private long currentIndex = -1;
/** The last element of the sequence, or -1 if the sequence is empty. */
private final long lastElement = isEmpty() ? -1 : getLong(size64() - 1);
/** The first element of the sequence, or {@link Long#MAX_VALUE} if the sequence is empty. */
private final long firstElement = isEmpty() ? Long.MAX_VALUE : getLong(0);
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final ByteIterable list) {
super(list);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final IntIterable list) {
super(list);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long length, final int l, final long[] lowerBits, final SimpleSelect selectUpper) {
super(length, l, lowerBits, selectUpper);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final ByteIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final IntIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final LongIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long n, final long upperBound, final ShortIterator iterator) {
super(n, upperBound, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final long[] a, final LongIterator iterator) {
super(a, iterator);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final LongIterable list) {
super(list);
}
/** {@inheritDoc} */
public EliasFanoIndexedMonotoneLongBigList(final ShortIterable list) {
super(list);
}
/**
* Returns the first element of the sequence that is greater than or equal to the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the first value of the sequence that is greater than or equal to {@code lowerBound}, or
* {@link Long#MAX_VALUE} if no such value exists.
* @see #strictSuccessor(long)
*/
public long successor(final long lowerBound) {
if (lowerBound <= firstElement) {
currentIndex = 0;
return firstElement;
}
if (lowerBound > lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
final long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
long rank = zeroesToSkip == 0 ? 0 : position - zeroesToSkip + 1;
if (l == 0) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
currentIndex = rank;
return upperBits;
} else {
long lowerBitsOffset = rank * l;
final int m = Long.SIZE - l;
for (;;) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
final long lower = lowerBits[startWord] >>> startBit;
final long v = upperBits << l | (startBit <= m ? lower : lower | lowerBits[startWord + 1] << -startBit) & lowerBitsMask;
if (v >= lowerBound) {
currentIndex = rank;
return v;
}
window &= window - 1;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the index of first element of the sequence that is greater than or equal to the provided
* bound.
*
* <p>
* This method is significantly faster than {@link #successor(long)}, as it does not have to compute
* the actual successor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the index of the first value of the sequence that is greater than or equal to
* {@code lowerBound}, or {@link Long#MAX_VALUE} if no such value exists.
* @see #successor(long)
*/
public long successorIndex(final long lowerBound) {
if (lowerBound <= firstElement) return 0;
if (lowerBound > lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1) + 1;
long rank = position - zeroesToSkip;
if (l == 0) return rank;
else {
long lowerBitsOffset = rank * l;
final long lowerBoundLowerBits = lowerBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
long lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower >= lowerBoundLowerBits) return rank;
position++;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the first element of the sequence that is greater than the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the first value of the sequence that is greater than {@code lowerBound}, or
* {@link Long#MAX_VALUE} if no such value exists.
* @see #successor(long)
*/
public long strictSuccessor(final long lowerBound) {
if (lowerBound < firstElement) {
currentIndex = 0;
return firstElement;
}
if (lowerBound >= lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
if (l == 0) {
final long position = selectUpperZero.selectZero(zeroesToSkip);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
final long rank = position - zeroesToSkip;
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
currentIndex = rank;
return upperBits;
} else {
final long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
long rank = zeroesToSkip == 0 ? 0 : position - zeroesToSkip + 1;
long lowerBitsOffset = rank * l;
final int m = Long.SIZE - l;
for (;;) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
final long lower = lowerBits[startWord] >>> startBit;
final long v = upperBits << l | (startBit <= m ? lower : lower | lowerBits[startWord + 1] << -startBit) & lowerBitsMask;
if (v > lowerBound) {
currentIndex = rank;
return v;
}
window &= window - 1;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the index of first element of the sequence that is greater than the provided bound.
*
* <p>
* This method is significantly faster than {@link #strictSuccessor(long)}, as it does not have to
* compute the actual strict successor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param lowerBound a lower bound on the returned value.
* @return the index of the first value of the sequence that is greater than {@code lowerBound}, or
* {@link Long#MAX_VALUE} if no such value exists.
* @see #strictSuccessor(long)
*/
public long strictSuccessorIndex(final long lowerBound) {
if (lowerBound < firstElement) return 0;
if (lowerBound >= lastElement) return Long.MAX_VALUE;
final long zeroesToSkip = lowerBound >>> l;
if (l == 0) {
final long position = selectUpperZero.selectZero(zeroesToSkip);
return position - zeroesToSkip;
} else {
long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1) + 1;
long rank = position - zeroesToSkip;
long lowerBitsOffset = rank * l;
final long lowerBoundLowerBits = lowerBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
long lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower > lowerBoundLowerBits) return rank;
position++;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns the last value of the sequence that is less than the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param upperBound a strict upper bound on the returned value.
* @return the last value of the sequence that is less than {@code upperBound}, or
* {@link Long#MIN_VALUE} if no such value exists.
* @see #weakPredecessor(long)
*/
public long predecessor(final long upperBound) {
if (upperBound <= firstElement) return Long.MIN_VALUE;
if (upperBound > lastElement) {
currentIndex = length - 1;
return lastElement;
}
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) {
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) break;
position--;
rank--;
}
currentIndex = rank;
return selectUpper.select(rank) - rank;
} else {
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if ((upperBits[word(position)] & 1L << position) == 0) {
int zeros = -(int)(Long.SIZE - position % Long.SIZE);
int curr = word(position);
long window = upperBits[curr] & ~(-1L << position);
while (window == 0) {
window = upperBits[--curr];
zeros += Long.SIZE;
}
currentIndex = rank;
return position - zeros - Long.numberOfLeadingZeros(window) - rank - 1 << l | lower;
}
if (lower < upperBoundLowerBits) {
currentIndex = rank;
return position - rank << l | lower;
}
lowerBitsOffset -= l;
position--;
rank--;
}
}
}
/**
* Returns the index of the last value of the sequence that is less than the provided bound.
*
* <p>
* This method is significantly faster than {@link #predecessor(long)}, as it does not have to
* compute the actual predecessor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param upperBound an upper bound on the returned value.
* @return the index of the last value of the sequence that is less than {@code upperBound}, or
* {@link Long#MIN_VALUE} if no such value exists.
* @see #predecessor(long)
*/
public long predecessorIndex(final long upperBound) {
if (upperBound <= firstElement) return Long.MIN_VALUE;
if (upperBound > lastElement) return length - 1;
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) {
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
position--;
rank--;
}
} else {
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower < upperBoundLowerBits) return rank;
rank--;
position--;
lowerBitsOffset -= l;
}
}
}
/**
* Returns the last value of the sequence that is less than or equal to the provided bound.
*
* <p>
* If such an element exists, its position in the sequence can be retrieved using {@link #index()}.
*
* @param upperBound an upper bound on the returned value.
* @return the last value of the sequence that is less than or equal to {@code upperBound}, or
* {@link Long#MIN_VALUE} if no such value exists.
* @see #predecessor(long)
*/
public long weakPredecessor(final long upperBound) {
if (upperBound < firstElement) return Long.MIN_VALUE;
if (upperBound >= lastElement) {
currentIndex = length - 1;
return lastElement;
}
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) {
currentIndex = rank;
return selectUpper.select(rank) - rank;
} else {
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if ((upperBits[word(position)] & 1L << position) == 0) {
currentIndex = rank;
do position--; while ((upperBits[word(position)] & 1L << position) == 0);
return position - rank << l | lower;
}
if (lower <= upperBoundLowerBits) {
currentIndex = rank;
return position - rank << l | lower;
}
rank--;
lowerBitsOffset -= l;
position--;
}
}
}
/**
* Returns the index of the last value of the sequence that is less than or equal to the provided
* bound.
*
* <p>
* This method is significantly faster than {@link #weakPredecessor(long)}, as it does not have to
* compute the actual weak predecessor.
*
* <p>
* Note that this method does not change the return value of {@link #index()}.
*
* @param upperBound an upper bound on the returned value.
* @return the index of the last value of the sequence that is less than or equal to
* {@code upperBound}, or {@link Long#MIN_VALUE} if no such value exists.
* @see #weakPredecessor(long)
*/
public long weakPredecessorIndex(final long upperBound) {
if (upperBound < firstElement) return Long.MIN_VALUE;
if (upperBound >= lastElement) return length - 1;
final long zeroesToSkip = upperBound >>> l;
long position = selectUpperZero.selectZero(zeroesToSkip) - 1;
long rank = position - zeroesToSkip;
if (l == 0) return rank;
long lowerBitsOffset = rank * l;
long lower;
final long upperBoundLowerBits = upperBound & lowerBitsMask;
final int m = Long.SIZE - l;
for (;;) {
if ((upperBits[word(position)] & 1L << position) == 0) return rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
lower = lowerBits[startWord] >>> startBit;
if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
lower &= lowerBitsMask;
if (lower <= upperBoundLowerBits) return rank;
rank--;
position--;
lowerBitsOffset -= l;
}
}
/**
* Returns the index of the first occurrence of the specified element in the sequence, or -1 if the
* element does not belong to the sequence.
*
* <p>
* This method does not change the value returned by {@link #index()}.
*
* @param x a long.
*/
@Override
public long indexOf(final long x) {
if (x < firstElement || x > lastElement) return -1;
final long zeroesToSkip = x >>> l;
final long position = zeroesToSkip == 0 ? 0 : selectUpperZero.selectZero(zeroesToSkip - 1);
int curr = word(position);
long window = upperBits[curr];
window &= -1L << position;
long rank = zeroesToSkip == 0 ? 0 : position - zeroesToSkip + 1;
if (l == 0) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
return upperBits == x ? rank : -1;
} else {
long lowerBitsOffset = rank * l;
final int m = Long.SIZE - l;
for (;;) {
while (window == 0) window = upperBits[++curr];
final long upperBits = bits(curr) + Long.numberOfTrailingZeros(window) - rank;
final int startWord = word(lowerBitsOffset);
final int startBit = bit(lowerBitsOffset);
final long lower = lowerBits[startWord] >>> startBit;
final long v = upperBits << l | (startBit <= m ? lower : lower | lowerBits[startWord + 1] << -startBit) & lowerBitsMask;
if (v >= x) return v == x ? rank : -1;
window &= window - 1;
rank++;
lowerBitsOffset += l;
}
}
}
/**
* Returns true if the sequence contains the specified element.
*
* <p>
* This method does not change the value returned by {@link #index()}. Use {@link #indexOf(long)} if
* you need to retrieve the position of an element.
*
* @param x a long.
* @return true if the sequence contains {@code x}.
*/
@Override
public boolean contains(final long x) {
return indexOf(x) != -1;
}
/**
* Returns the index realizing the last value returned by {@link #predecessor(long)},
* {@link #weakPredecessor(long)}, {@link #successor(long)}, and {@link #strictSuccessor(long)}.
*
* <p>
* Usage of this method makes instances of this class not thread safe, as the return value is cached
* internally.
*
* @return the index of the element realizing the last value returned by {@link #predecessor(long)},
* {@link #weakPredecessor(long)}, {@link #successor(long)}, and
* {@link #strictSuccessor(long)}, or -1 if no such method has ever been called.
*/
public long index() {
return currentIndex;
}
}
|
Slightly faster implementations
|
src/it/unimi/dsi/sux4j/util/EliasFanoIndexedMonotoneLongBigList.java
|
Slightly faster implementations
|
<ide><path>rc/it/unimi/dsi/sux4j/util/EliasFanoIndexedMonotoneLongBigList.java
<ide> if (startBit > m) lower |= lowerBits[startWord + 1] << -startBit;
<ide> lower &= lowerBitsMask;
<ide> if ((upperBits[word(position)] & 1L << position) == 0) {
<del> int zeros = -(int)(Long.SIZE - position % Long.SIZE);
<add> int zeros = (int)(position | -Long.SIZE); // == - (Long.SIZE - (position % Long.SIZE))
<ide> int curr = word(position);
<ide> long window = upperBits[curr] & ~(-1L << position);
<ide> while (window == 0) {
<ide> lower &= lowerBitsMask;
<ide>
<ide> if ((upperBits[word(position)] & 1L << position) == 0) {
<add> int zeros = (int)(position | -Long.SIZE); // == - (Long.SIZE - (position % Long.SIZE))
<add> int curr = word(position);
<add> long window = upperBits[curr] & ~(-1L << position);
<add> while (window == 0) {
<add> window = upperBits[--curr];
<add> zeros += Long.SIZE;
<add> }
<ide> currentIndex = rank;
<del> do position--; while ((upperBits[word(position)] & 1L << position) == 0);
<del> return position - rank << l | lower;
<add> return position - zeros - Long.numberOfLeadingZeros(window) - rank - 1 << l | lower;
<ide> }
<ide>
<ide> if (lower <= upperBoundLowerBits) {
|
|
JavaScript
|
mit
|
a0867dff7f0d21e86f22947b932973806548d8be
| 0 |
MichinobuMaeda/tamuro.ui,MichinobuMaeda/tamuro.ui,MichinobuMaeda/tamuro.ui
|
import axios from 'axios'
export const releaseUiNewVersion = ({ state }) => state.db.collection('service').doc('status').update({
version: state.conf.version
})
const onServiceStatusChanged = async ({ commit, state }, { doc, i18n }) => {
commit('setService', doc)
i18n.locale = (state.service && state.service.status && state.service.status.locale) || i18n.locale
if (state.service.status.version > state.conf.version) {
const headers = {
'Pragma': 'no-cache',
'Expires': -1,
'Cache-Control': 'no-cache'
}
await axios.get(window.location.href, { headers })
await axios.get(window.location.href.replace(/#.*/, '').replace(/\/[^/]*$/, '/service-worker.js'), { headers })
window.location.href = '' + window.location.href
}
}
export const getServiceStatus = async ({ commit, state }, { i18n }) => {
await onServiceStatusChanged({ commit, state }, { doc: await state.db.collection('service').doc('status').get(), i18n })
state.db.collection('service').doc('status').onSnapshot(async doc => {
await onServiceStatusChanged({ commit, state }, { doc, i18n })
})
}
|
src/store/actionsService.js
|
import axios from 'axios'
export const releaseUiNewVersion = ({ state }) => state.db.collection('service').doc('status').update({
version: state.conf.version
})
const onServiceStatusChanged = async ({ commit, state }, { doc, i18n }) => {
commit('setService', doc)
i18n.locale = (state.service && state.service.status && state.service.status.locale) || i18n.locale
if (state.service.status.version > state.conf.version) {
const headers = {
'Pragma': 'no-cache',
'Expires': -1,
'Cache-Control': 'no-cache'
}
await axios.get(window.location.href, { headers })
await axios.get(window.location.href.replace(/#.*/, '').replace(/\/[^/]*$/, '/service-worker.js'), { headers })
window.location.href = window.location.href
}
}
export const getServiceStatus = async ({ commit, state }, { i18n }) => {
await onServiceStatusChanged({ commit, state }, { doc: await state.db.collection('service').doc('status').get(), i18n })
state.db.collection('service').doc('status').onSnapshot(async doc => {
await onServiceStatusChanged({ commit, state }, { doc, i18n })
})
}
|
test: UI update
|
src/store/actionsService.js
|
test: UI update
|
<ide><path>rc/store/actionsService.js
<ide> }
<ide> await axios.get(window.location.href, { headers })
<ide> await axios.get(window.location.href.replace(/#.*/, '').replace(/\/[^/]*$/, '/service-worker.js'), { headers })
<del> window.location.href = window.location.href
<add> window.location.href = '' + window.location.href
<ide> }
<ide> }
<ide>
|
|
JavaScript
|
agpl-3.0
|
1f36bcd8bedf74063be00ccdfa04ab43a98179e9
| 0 |
ryo33/Yayaka19,ryo33/Yayaka19
|
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import createHistory from 'history/createBrowserHistory'
import { signedIn, userID } from './global.js'
import App from './components/App.js'
import { pages, pagesMiddleware } from './pages.js'
import reducer from './reducers/index.js'
import { pageSelector } from './selectors.js'
import middleware from './middlewares.js'
import {
addFavs, updateTimeline, setUser,
setFollowing, updateNoticed, updateNotices,
showError, hideError
} from './actions.js'
import { joinChannel, joinUserChannel } from './socket.js'
import { watchUserChannel } from './userChannel.js'
// Create the pagesMiddleware
const history = createHistory({})
const getCurrentPath = () => history.location.pathname
const pushPath = (path) => history.push(path)
const reduxPagesMiddleware = pages
.middleware(pageSelector, getCurrentPath, pushPath)
// Create the store
const middlewares = [middleware]
if (process.env.NODE_ENV !== 'production') {
const logger = createLogger()
middlewares.push(logger)
}
const store = createStore(
reducer,
applyMiddleware(reduxPagesMiddleware, pagesMiddleware, ...middlewares),
)
// Socket
const userChannelCallback = ({ user, noticed, following, notices, timeline }) => {
const { favs, posts } = timeline
store.dispatch(setUser(user))
store.dispatch(addFavs(favs))
store.dispatch(updateTimeline(posts))
store.dispatch(updateNoticed(noticed))
store.dispatch(updateNotices(notices))
store.dispatch(setFollowing(following))
}
if (signedIn) {
joinUserChannel(userChannelCallback)
watchUserChannel(store)
}
const respCallback = () => {
store.dispatch(hideError())
// Apply the current path
pages.handleNavigation(store, history.location.pathname)
}
const errorCallback = () => {
store.dispatch(showError('Failed to connect to the server.'))
}
joinChannel(respCallback, errorCallback)
// Listen for changes
history.listen((location, action) => {
pages.handleNavigation(store, location.pathname)
})
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
web/static/js/app.js
|
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import createHistory from 'history/createBrowserHistory'
import { signedIn, userID } from './global.js'
import App from './components/App.js'
import { pages, pagesMiddleware } from './pages.js'
import reducer from './reducers/index.js'
import { pageSelector } from './selectors.js'
import middleware from './middlewares.js'
import {
addFavs, updateTimeline, setUser,
setFollowing, updateNoticed, updateNotices,
showError
} from './actions.js'
import { joinChannel, joinUserChannel } from './socket.js'
import { watchUserChannel } from './userChannel.js'
// Create the pagesMiddleware
const history = createHistory({})
const getCurrentPath = () => history.location.pathname
const pushPath = (path) => history.push(path)
const reduxPagesMiddleware = pages
.middleware(pageSelector, getCurrentPath, pushPath)
// Create the store
const middlewares = [middleware]
if (process.env.NODE_ENV !== 'production') {
const logger = createLogger()
middlewares.push(logger)
}
const store = createStore(
reducer,
applyMiddleware(reduxPagesMiddleware, pagesMiddleware, ...middlewares),
)
// Socket
const userChannelCallback = ({ user, noticed, following, notices, timeline }) => {
const { favs, posts } = timeline
store.dispatch(setUser(user))
store.dispatch(addFavs(favs))
store.dispatch(updateTimeline(posts))
store.dispatch(updateNoticed(noticed))
store.dispatch(updateNotices(notices))
store.dispatch(setFollowing(following))
}
if (signedIn) {
joinUserChannel(userChannelCallback)
watchUserChannel(store)
}
const respCallback = () => {
// Apply the current path
pages.handleNavigation(store, history.location.pathname)
}
const errorCallback = () => {
store.dispatch(showError('Failed to connect to the server.'))
}
joinChannel(respCallback, errorCallback)
// Listen for changes
history.listen((location, action) => {
pages.handleNavigation(store, location.pathname)
})
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
Hide error message automatically
|
web/static/js/app.js
|
Hide error message automatically
|
<ide><path>eb/static/js/app.js
<ide> import {
<ide> addFavs, updateTimeline, setUser,
<ide> setFollowing, updateNoticed, updateNotices,
<del> showError
<add> showError, hideError
<ide> } from './actions.js'
<ide> import { joinChannel, joinUserChannel } from './socket.js'
<ide> import { watchUserChannel } from './userChannel.js'
<ide> }
<ide>
<ide> const respCallback = () => {
<add> store.dispatch(hideError())
<ide> // Apply the current path
<ide> pages.handleNavigation(store, history.location.pathname)
<ide> }
|
|
Java
|
epl-1.0
|
c3273b119b5e25f64ad8ab085bc54cdcf97297d8
| 0 |
akervern/che,davidfestal/che,akervern/che,akervern/che,davidfestal/che,akervern/che,davidfestal/che,davidfestal/che,davidfestal/che,akervern/che,codenvy/che,akervern/che,akervern/che,davidfestal/che,davidfestal/che,davidfestal/che,codenvy/che,akervern/che,akervern/che,codenvy/che,codenvy/che,davidfestal/che,davidfestal/che
|
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.selenium.dashboard.organization;
import static org.eclipse.che.commons.lang.NameGenerator.generate;
import static org.eclipse.che.selenium.pageobject.dashboard.NavigationBar.MenuItem.ORGANIZATIONS;
import static org.eclipse.che.selenium.pageobject.dashboard.organization.OrganizationListPage.OrganizationListHeader.NAME;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import com.google.inject.Inject;
import org.eclipse.che.selenium.core.TestGroup;
import org.eclipse.che.selenium.core.organization.InjectTestOrganization;
import org.eclipse.che.selenium.core.organization.TestOrganization;
import org.eclipse.che.selenium.core.user.AdminTestUser;
import org.eclipse.che.selenium.core.user.TestUser;
import org.eclipse.che.selenium.pageobject.dashboard.Dashboard;
import org.eclipse.che.selenium.pageobject.dashboard.EditMode;
import org.eclipse.che.selenium.pageobject.dashboard.NavigationBar;
import org.eclipse.che.selenium.pageobject.dashboard.organization.OrganizationListPage;
import org.eclipse.che.selenium.pageobject.dashboard.organization.OrganizationPage;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Test validates organization rename.
*
* @author Ann Shumilova
*/
@Test(groups = {TestGroup.MULTIUSER})
public class RenameOrganizationTest {
private static final String NEW_PARENT_ORG_NAME = generate("new-parent-", 5);
private static final String NEW_CHILD_ORG_NAME = generate("new-child-", 5);
// more than 20 symbols
private static final String TOO_LONG_ORG_NAME = generate("too-long-org-name-", 10);
private static final String EMPTY_ORGANIZATION_NAME = " ";
private static final String ORG_NAME_WITH_INVALID_CHARS = "_organization$";
@InjectTestOrganization(prefix = "parentOrg")
private TestOrganization parentOrg;
@InjectTestOrganization(parentPrefix = "parentOrg")
private TestOrganization childOrg;
@Inject private OrganizationListPage organizationListPage;
@Inject private OrganizationPage organizationPage;
@Inject private NavigationBar navigationBar;
@Inject private EditMode editMode;
@Inject private Dashboard dashboard;
@Inject private TestUser testUser;
@Inject private AdminTestUser adminTestUser;
@BeforeClass
public void setUp() throws Exception {
parentOrg.addAdmin(testUser.getId());
childOrg.addAdmin(testUser.getId());
dashboard.open(testUser.getName(), testUser.getPassword());
}
public void testParentOrganizationRename() {
navigationBar.waitNavigationBar();
navigationBar.clickOnMenu(ORGANIZATIONS);
organizationListPage.waitForOrganizationsToolbar();
organizationListPage.waitForOrganizationsList();
organizationListPage.clickOnOrganization(parentOrg.getName());
// Check organization renaming with name just ' '
renameOrganizationWithInvalidName(EMPTY_ORGANIZATION_NAME);
// Check organization renaming with name more than 20 symbols
renameOrganizationWithInvalidName(TOO_LONG_ORG_NAME);
// Check organization renaming with name that contains invalid characters
renameOrganizationWithInvalidName(ORG_NAME_WITH_INVALID_CHARS);
// Test renaming of the parent organization
organizationPage.waitOrganizationTitle(parentOrg.getName());
organizationPage.setOrganizationName(NEW_PARENT_ORG_NAME);
editMode.waitDisplayed();
assertTrue(editMode.isSaveEnabled());
editMode.clickSave();
editMode.waitHidden();
organizationPage.waitOrganizationTitle(NEW_PARENT_ORG_NAME);
assertEquals(NEW_PARENT_ORG_NAME, organizationPage.getOrganizationName());
}
@Test(priority = 1)
public void testSubOrganizationRename() {
String childOrgQualifiedName = NEW_PARENT_ORG_NAME + "/" + childOrg.getName();
String newChildOrgQualifiedName = NEW_PARENT_ORG_NAME + "/" + NEW_CHILD_ORG_NAME;
navigationBar.waitNavigationBar();
navigationBar.clickOnMenu(ORGANIZATIONS);
organizationListPage.waitForOrganizationsToolbar();
organizationListPage.waitForOrganizationsList();
// Test renaming of the child organization
organizationListPage.clickOnOrganization(childOrgQualifiedName);
organizationPage.waitOrganizationTitle(childOrgQualifiedName);
organizationPage.setOrganizationName(NEW_CHILD_ORG_NAME);
editMode.waitDisplayed();
assertTrue(editMode.isSaveEnabled());
editMode.clickSave();
editMode.waitHidden();
organizationPage.waitOrganizationTitle(newChildOrgQualifiedName);
assertEquals(organizationPage.getOrganizationName(), NEW_CHILD_ORG_NAME);
// Back to the parent organization and test that the child organization renamed
organizationPage.clickBackButton();
organizationPage.waitOrganizationTitle(NEW_PARENT_ORG_NAME);
organizationPage.clickSubOrganizationsTab();
organizationListPage.waitForOrganizationsList();
assertTrue(organizationListPage.getValues(NAME).contains(newChildOrgQualifiedName));
// Back to the Organizations list and test that the organizations renamed
organizationPage.clickBackButton();
organizationListPage.waitForOrganizationsList();
try {
assertTrue(organizationListPage.getValues(NAME).contains(newChildOrgQualifiedName));
} catch (AssertionError ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che/issues/8668");
}
assertTrue(organizationListPage.getValues(NAME).contains(NEW_PARENT_ORG_NAME));
}
private void renameOrganizationWithInvalidName(String organizationName) {
organizationPage.waitOrganizationTitle(parentOrg.getName());
organizationPage.setOrganizationName(organizationName);
editMode.waitDisplayed();
assertFalse(editMode.isSaveEnabled());
editMode.clickCancel();
editMode.waitHidden();
assertEquals(parentOrg.getName(), organizationPage.getOrganizationName());
}
}
|
selenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/dashboard/organization/RenameOrganizationTest.java
|
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.selenium.dashboard.organization;
import static org.eclipse.che.commons.lang.NameGenerator.generate;
import static org.eclipse.che.selenium.pageobject.dashboard.NavigationBar.MenuItem.ORGANIZATIONS;
import static org.eclipse.che.selenium.pageobject.dashboard.organization.OrganizationListPage.OrganizationListHeader.NAME;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import com.google.inject.Inject;
import org.eclipse.che.selenium.core.TestGroup;
import org.eclipse.che.selenium.core.organization.InjectTestOrganization;
import org.eclipse.che.selenium.core.organization.TestOrganization;
import org.eclipse.che.selenium.core.user.AdminTestUser;
import org.eclipse.che.selenium.core.user.TestUser;
import org.eclipse.che.selenium.pageobject.dashboard.Dashboard;
import org.eclipse.che.selenium.pageobject.dashboard.EditMode;
import org.eclipse.che.selenium.pageobject.dashboard.NavigationBar;
import org.eclipse.che.selenium.pageobject.dashboard.organization.OrganizationListPage;
import org.eclipse.che.selenium.pageobject.dashboard.organization.OrganizationPage;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Test validates organization rename.
*
* @author Ann Shumilova
*/
@Test(groups = {TestGroup.MULTIUSER})
public class RenameOrganizationTest {
private static final String NEW_PARENT_ORG_NAME = generate("new-parent-", 5);
private static final String NEW_CHILD_ORG_NAME = generate("new-child-", 5);
// more than 20 symbols
private static final String TOO_LONG_ORG_NAME = generate("too-long-org-name-", 10);
private static final String EMPTY_ORGANIZATION_NAME = " ";
private static final String ORG_NAME_WITH_INVALID_CHARS = "_organization$";
@InjectTestOrganization(prefix = "parentOrg")
private TestOrganization parentOrg;
@InjectTestOrganization(parentPrefix = "parentOrg")
private TestOrganization childOrg;
@Inject private OrganizationListPage organizationListPage;
@Inject private OrganizationPage organizationPage;
@Inject private NavigationBar navigationBar;
@Inject private EditMode editMode;
@Inject private Dashboard dashboard;
@Inject private TestUser testUser;
@Inject private AdminTestUser adminTestUser;
@BeforeClass
public void setUp() throws Exception {
parentOrg.addAdmin(testUser.getId());
childOrg.addAdmin(testUser.getId());
dashboard.open(testUser.getName(), testUser.getPassword());
}
public void testParentOrganizationRename() {
navigationBar.waitNavigationBar();
navigationBar.clickOnMenu(ORGANIZATIONS);
organizationListPage.waitForOrganizationsToolbar();
organizationListPage.waitForOrganizationsList();
organizationListPage.clickOnOrganization(parentOrg.getName());
// Check organization renaming with name just ' '
renameOrganizationWithInvalidName(EMPTY_ORGANIZATION_NAME);
// Check organization renaming with name more than 20 symbols
renameOrganizationWithInvalidName(TOO_LONG_ORG_NAME);
// Check organization renaming with name that contains invalid characters
renameOrganizationWithInvalidName(ORG_NAME_WITH_INVALID_CHARS);
// Test renaming of the parent organization
organizationPage.waitOrganizationTitle(parentOrg.getName());
organizationPage.setOrganizationName(NEW_PARENT_ORG_NAME);
editMode.waitDisplayed();
assertTrue(editMode.isSaveEnabled());
editMode.clickSave();
editMode.waitHidden();
organizationPage.waitOrganizationTitle(NEW_PARENT_ORG_NAME);
assertEquals(NEW_PARENT_ORG_NAME, organizationPage.getOrganizationName());
}
@Test(priority = 1)
public void testSubOrganizationRename() {
String childOrgQualifiedName = NEW_PARENT_ORG_NAME + "/" + childOrg.getName();
String newChildOrgQualifiedName = NEW_PARENT_ORG_NAME + "/" + NEW_CHILD_ORG_NAME;
navigationBar.waitNavigationBar();
navigationBar.clickOnMenu(ORGANIZATIONS);
organizationListPage.waitForOrganizationsToolbar();
organizationListPage.waitForOrganizationsList();
// Test renaming of the child organization
organizationListPage.clickOnOrganization(childOrgQualifiedName);
organizationPage.waitOrganizationTitle(childOrgQualifiedName);
organizationPage.setOrganizationName(NEW_CHILD_ORG_NAME);
editMode.waitDisplayed();
assertTrue(editMode.isSaveEnabled());
editMode.clickSave();
editMode.waitHidden();
organizationPage.waitOrganizationTitle(newChildOrgQualifiedName);
assertEquals(organizationPage.getOrganizationName(), NEW_CHILD_ORG_NAME);
// Back to the parent organization and test that the child organization renamed
organizationPage.clickBackButton();
organizationPage.waitOrganizationTitle(NEW_PARENT_ORG_NAME);
organizationPage.clickSubOrganizationsTab();
organizationListPage.waitForOrganizationsList();
assertTrue(organizationListPage.getValues(NAME).contains(newChildOrgQualifiedName));
// Back to the Organizations list and test that the organizations renamed
organizationPage.clickBackButton();
organizationListPage.waitForOrganizationsList();
assertTrue(organizationListPage.getValues(NAME).contains(newChildOrgQualifiedName));
assertTrue(organizationListPage.getValues(NAME).contains(NEW_PARENT_ORG_NAME));
}
private void renameOrganizationWithInvalidName(String organizationName) {
organizationPage.waitOrganizationTitle(parentOrg.getName());
organizationPage.setOrganizationName(organizationName);
editMode.waitDisplayed();
assertFalse(editMode.isSaveEnabled());
editMode.clickCancel();
editMode.waitHidden();
assertEquals(parentOrg.getName(), organizationPage.getOrganizationName());
}
}
|
Selenium: add info about issue #8668 to RenameOrganizationTest (#8670)
|
selenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/dashboard/organization/RenameOrganizationTest.java
|
Selenium: add info about issue #8668 to RenameOrganizationTest (#8670)
|
<ide><path>elenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/dashboard/organization/RenameOrganizationTest.java
<ide> import static org.testng.Assert.assertEquals;
<ide> import static org.testng.Assert.assertFalse;
<ide> import static org.testng.Assert.assertTrue;
<add>import static org.testng.Assert.fail;
<ide>
<ide> import com.google.inject.Inject;
<ide> import org.eclipse.che.selenium.core.TestGroup;
<ide> // Back to the Organizations list and test that the organizations renamed
<ide> organizationPage.clickBackButton();
<ide> organizationListPage.waitForOrganizationsList();
<del> assertTrue(organizationListPage.getValues(NAME).contains(newChildOrgQualifiedName));
<add>
<add> try {
<add> assertTrue(organizationListPage.getValues(NAME).contains(newChildOrgQualifiedName));
<add> } catch (AssertionError ex) {
<add> // remove try-catch block after issue has been resolved
<add> fail("Known issue https://github.com/eclipse/che/issues/8668");
<add> }
<add>
<ide> assertTrue(organizationListPage.getValues(NAME).contains(NEW_PARENT_ORG_NAME));
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
5ec13e7dbcb75bb3d4147ed5d30f73cb8699e1e3
| 0 |
zazi/dswarm,knutwalker/dswarm,philbritton/dswarm,janpolowinski/dswarm,dswarm/dswarm,janpolowinski/dswarm,zazi/dswarm,knutwalker/dswarm,dswarm/dswarm,dswarm/dswarm,knutwalker/dswarm,philbritton/dswarm,philbritton/dswarm,zazi/dswarm
|
package de.avgl.dmp.persistence.service.internal.graph;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import de.avgl.dmp.graph.json.Resource;
import de.avgl.dmp.graph.json.util.Util;
import de.avgl.dmp.persistence.DMPPersistenceException;
import de.avgl.dmp.persistence.model.internal.Model;
import de.avgl.dmp.persistence.model.internal.gdm.GDMModel;
import de.avgl.dmp.persistence.model.internal.helper.AttributePathHelper;
import de.avgl.dmp.persistence.model.proxy.RetrievalType;
import de.avgl.dmp.persistence.model.resource.DataModel;
import de.avgl.dmp.persistence.model.resource.proxy.ProxyDataModel;
import de.avgl.dmp.persistence.model.schema.Attribute;
import de.avgl.dmp.persistence.model.schema.AttributePath;
import de.avgl.dmp.persistence.model.schema.Clasz;
import de.avgl.dmp.persistence.model.schema.Schema;
import de.avgl.dmp.persistence.model.schema.proxy.ProxyAttribute;
import de.avgl.dmp.persistence.model.schema.proxy.ProxyAttributePath;
import de.avgl.dmp.persistence.model.schema.proxy.ProxyClasz;
import de.avgl.dmp.persistence.model.schema.proxy.ProxySchema;
import de.avgl.dmp.persistence.model.schema.utils.SchemaUtils;
import de.avgl.dmp.persistence.service.InternalModelService;
import de.avgl.dmp.persistence.service.resource.DataModelService;
import de.avgl.dmp.persistence.service.schema.AttributePathService;
import de.avgl.dmp.persistence.service.schema.AttributeService;
import de.avgl.dmp.persistence.service.schema.ClaszService;
import de.avgl.dmp.persistence.service.schema.SchemaService;
import de.avgl.dmp.persistence.util.DMPPersistenceUtil;
import de.avgl.dmp.persistence.util.GDMUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A internal model service implementation for RDF triples.<br/>
* Currently, the Neo4j database is utilised.
*
* @author tgaengler
*/
@Singleton
public class InternalGDMGraphService implements InternalModelService {
private static final Logger LOG = LoggerFactory.getLogger(InternalGDMGraphService.class);
private static final String resourceIdentifier = "gdm";
/**
* The data model persistence service.
*/
private final Provider<DataModelService> dataModelService;
/**
* The schema persistence service.
*/
private final Provider<SchemaService> schemaService;
/**
* The class persistence service.
*/
private final Provider<ClaszService> classService;
private final Provider<AttributePathService> attributePathService;
private final Provider<AttributeService> attributeService;
/**
* The data model graph URI pattern
*/
private static final String DATA_MODEL_GRAPH_URI_PATTERN = "http://data.slub-dresden.de/datamodel/{datamodelid}/data";
private final String graphEndpoint;
/**
* /** Creates a new internal triple service with the given data model persistence service, schema persistence service, class
* persistence service and the endpoint to access the graph database.
*
* @param dataModelService the data model persistence service
* @param schemaService the schema persistence service
* @param classService the class persistence service
* @param attributePathService the attribute path persistence service
* @param attributeService the attribute persistence service
* @param graphEndpointArg the endpoint to access the graph database
*/
@Inject
public InternalGDMGraphService(final Provider<DataModelService> dataModelService, final Provider<SchemaService> schemaService,
final Provider<ClaszService> classService, final Provider<AttributePathService> attributePathService,
final Provider<AttributeService> attributeService, @Named("dmp_graph_endpoint") final String graphEndpointArg) {
this.dataModelService = dataModelService;
this.schemaService = schemaService;
this.classService = classService;
this.attributePathService = attributePathService;
this.attributeService = attributeService;
graphEndpoint = graphEndpointArg;
}
/**
* {@inheritDoc}
*/
@Override
public void createObject(final Long dataModelId, final Object model) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
if (model == null) {
throw new DMPPersistenceException("model that should be added to DB shouldn't be null");
}
if (!GDMModel.class.isInstance(model)) {
throw new DMPPersistenceException("this service can only process GDM models");
}
final GDMModel gdmModel = (GDMModel) model;
final de.avgl.dmp.graph.json.Model realModel = gdmModel.getModel();
if (realModel == null) {
throw new DMPPersistenceException("real model that should be added to DB shouldn't be null");
}
final String resourceGraphURI = InternalGDMGraphService.DATA_MODEL_GRAPH_URI_PATTERN.replace("{datamodelid}", dataModelId.toString());
final DataModel dataModel = addRecordClass(dataModelId, gdmModel.getRecordClassURI());
final DataModel finalDataModel;
if (dataModel != null) {
finalDataModel = dataModel;
} else {
finalDataModel = getDataModel(dataModelId);
}
if (finalDataModel.getSchema() != null) {
if (finalDataModel.getSchema().getRecordClass() != null) {
final String recordClassURI = finalDataModel.getSchema().getRecordClass().getUri();
final Set<Resource> recordResources = GDMUtil.getRecordResources(recordClassURI, realModel);
if (recordResources != null) {
final LinkedHashSet<String> recordURIs = Sets.newLinkedHashSet();
for (final Resource recordResource : recordResources) {
recordURIs.add(recordResource.getUri());
}
gdmModel.setRecordURIs(recordURIs);
}
}
}
addAttributePaths(finalDataModel, gdmModel.getAttributePaths());
writeGDMToDB(realModel, resourceGraphURI);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Map<String, Model>> getObjects(final Long dataModelId, final Optional<Integer> atMost) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
final String resourceGraphURI = InternalGDMGraphService.DATA_MODEL_GRAPH_URI_PATTERN.replace("{datamodelid}", dataModelId.toString());
// retrieve record class uri from data model schema
final DataModel dataModel = dataModelService.get().getObject(dataModelId);
if (dataModel == null) {
InternalGDMGraphService.LOG.debug("couldn't find data model '" + dataModelId + "' to retrieve record class from");
throw new DMPPersistenceException("couldn't find data model '" + dataModelId + "' to retrieve record class from");
}
final Schema schema = dataModel.getSchema();
if (schema == null) {
InternalGDMGraphService.LOG.debug("couldn't find schema in data model '" + dataModelId + "'");
throw new DMPPersistenceException("couldn't find schema in data model '" + dataModelId + "'");
}
final Clasz recordClass = schema.getRecordClass();
if (recordClass == null) {
InternalGDMGraphService.LOG.debug("couldn't find record class in schema '" + schema.getId() + "' of data model '" + dataModelId + "'");
throw new DMPPersistenceException("couldn't find record class in schema '" + schema.getId() + "' of data model '" + dataModelId + "'");
}
final String recordClassUri = recordClass.getUri();
final de.avgl.dmp.graph.json.Model model = readGDMFromDB(recordClassUri, resourceGraphURI);
if (model == null) {
InternalGDMGraphService.LOG.debug("couldn't find model for data model '" + dataModelId + "' in database");
return Optional.absent();
}
if (model.size() <= 0) {
InternalGDMGraphService.LOG.debug("model is empty for data model '" + dataModelId + "' in database");
return Optional.absent();
}
final Set<Resource> recordResources = GDMUtil.getRecordResources(recordClassUri, model);
if (recordResources == null || recordResources.isEmpty()) {
InternalGDMGraphService.LOG.debug("couldn't find records for record class'" + recordClassUri + "' in data model '" + dataModelId + "'");
throw new DMPPersistenceException("couldn't find records for record class'" + recordClassUri + "' in data model '" + dataModelId + "'");
}
final Map<String, Model> modelMap = Maps.newLinkedHashMap();
int i = 0;
for (final Resource recordResource : recordResources) {
if (atMost.isPresent()) {
if (i >= atMost.get()) {
break;
}
}
final de.avgl.dmp.graph.json.Model recordModel = new de.avgl.dmp.graph.json.Model();
recordModel.addResource(recordResource);
final Model rdfModel = new GDMModel(recordModel, recordResource.getUri());
modelMap.put(recordResource.getUri(), rdfModel);
i++;
}
return Optional.of(modelMap);
}
/**
* {@inheritDoc}
*/
@Override
public void deleteObject(final Long dataModelId) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
final String resourceGraphURI = InternalGDMGraphService.DATA_MODEL_GRAPH_URI_PATTERN.replace("{datamodelid}", dataModelId.toString());
// TODO: delete DataModel object from DB here as well?
// dataset.begin(ReadWrite.WRITE);
// dataset.removeNamedModel(resourceGraphURI);
// dataset.commit();
// dataset.end();
// TODO
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Schema> getSchema(final Long dataModelId) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
final DataModel dataModel = dataModelService.get().getObject(dataModelId);
if (dataModel == null) {
InternalGDMGraphService.LOG.debug("couldn't find data model '" + dataModelId + "' to retrieve it's schema");
throw new DMPPersistenceException("couldn't find data model '" + dataModelId + "' to retrieve it's schema");
}
final Schema schema = dataModel.getSchema();
if (schema == null) {
InternalGDMGraphService.LOG.debug("couldn't find schema in data model '" + dataModelId + "'");
return Optional.absent();
}
return Optional.of(schema);
}
/**
* Adds the record class to the schema of the data model.
*
* @param dataModelId the identifier of the data model
* @param recordClassUri the identifier of the record class
* @throws DMPPersistenceException
*/
private DataModel addRecordClass(final Long dataModelId, final String recordClassUri) throws DMPPersistenceException {
// (try) add record class uri to schema
final DataModel dataModel = getSchemaInternal(dataModelId);
final Schema schema = dataModel.getSchema();
final Clasz recordClass;
if (schema.getRecordClass() != null) {
if (schema.getRecordClass().getUri().equals(recordClassUri)) {
// nothing to do, record class is already set
return dataModel;
}
} else {
// create new class
final ProxyClasz proxyRecordClass = classService.get().createOrGetObjectTransactional(recordClassUri);
if (proxyRecordClass == null) {
throw new DMPPersistenceException("couldn't create or retrieve record class");
}
recordClass = proxyRecordClass.getObject();
if (proxyRecordClass.getType().equals(RetrievalType.CREATED)) {
if (recordClass == null) {
throw new DMPPersistenceException("couldn't create new record class");
}
final String recordClassName = SchemaUtils.determineRelativeURIPart(recordClassUri);
recordClass.setName(recordClassName);
}
schema.setRecordClass(recordClass);
}
final ProxyDataModel proxyUpdatedDataModel = dataModelService.get().updateObjectTransactional(dataModel);
if (proxyUpdatedDataModel == null) {
throw new DMPPersistenceException("couldn't update data model");
}
return proxyUpdatedDataModel.getObject();
}
private DataModel addAttributePaths(final DataModel dataModel, final Set<AttributePathHelper> attributePathHelpers)
throws DMPPersistenceException {
if (attributePathHelpers == null) {
InternalGDMGraphService.LOG.debug("couldn't determine attribute paths from data model '" + dataModel.getId() + "'");
return dataModel;
}
if (attributePathHelpers.isEmpty()) {
InternalGDMGraphService.LOG.debug("there are no attribute paths from data model '" + dataModel.getId() + "'");
}
for (final AttributePathHelper attributePathHelper : attributePathHelpers) {
final LinkedList<Attribute> attributes = Lists.newLinkedList();
final LinkedList<String> attributePathFromHelper = attributePathHelper.getAttributePath();
if (attributePathFromHelper.isEmpty()) {
InternalGDMGraphService.LOG.debug("there are no attributes for this attribute path from data model '" + dataModel.getId() + "'");
}
for (final String attributeString : attributePathFromHelper) {
final ProxyAttribute proxyAttribute = attributeService.get().createOrGetObjectTransactional(attributeString);
if (proxyAttribute == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute");
}
final Attribute attribute = proxyAttribute.getObject();
if (attribute == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute");
}
attributes.add(attribute);
final String attributeName = SchemaUtils.determineRelativeURIPart(attributeString);
attribute.setName(attributeName);
}
final ProxyAttributePath proxyAttributePath = attributePathService.get().createOrGetObjectTransactional(attributes);
if (proxyAttributePath == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute path");
}
final AttributePath attributePath = proxyAttributePath.getObject();
if (attributePath == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute path");
}
dataModel.getSchema().addAttributePath(attributePath);
}
final ProxyDataModel proxyUpdatedDataModel = dataModelService.get().updateObjectTransactional(dataModel);
if (proxyUpdatedDataModel == null) {
throw new DMPPersistenceException("couldn't update data model");
}
return proxyUpdatedDataModel.getObject();
}
private DataModel getSchemaInternal(final Long dataModelId) throws DMPPersistenceException {
final DataModel dataModel = getDataModel(dataModelId);
final Schema schema;
if (dataModel.getSchema() == null) {
// create new schema
final ProxySchema proxySchema = schemaService.get().createObjectTransactional();
if (proxySchema != null) {
schema = proxySchema.getObject();
} else {
schema = null;
}
dataModel.setSchema(schema);
}
return dataModel;
}
private DataModel getDataModel(final Long dataModelId) {
final DataModel dataModel = dataModelService.get().getObject(dataModelId);
if (dataModel == null) {
InternalGDMGraphService.LOG.debug("couldn't find data model '" + dataModelId + "'");
return null;
}
return dataModel;
}
private void writeGDMToDB(final de.avgl.dmp.graph.json.Model model, final String resourceGraphUri) throws DMPPersistenceException {
final WebTarget target = target("/put");
final ObjectMapper objectMapper = Util.getJSONObjectMapper();
byte[] bytes = null;
try {
bytes = objectMapper.writeValueAsBytes(model);
} catch (final JsonProcessingException e) {
throw new DMPPersistenceException("couldn't serialise model to JSON");
}
// Construct a MultiPart with two body parts
final MultiPart multiPart = new MultiPart();
multiPart.bodyPart(bytes, MediaType.APPLICATION_OCTET_STREAM_TYPE).bodyPart(resourceGraphUri, MediaType.TEXT_PLAIN_TYPE);
// POST the request
final Response response = target.request("multipart/mixed").post(Entity.entity(multiPart, "multipart/mixed"));
if (response.getStatus() != 200) {
throw new DMPPersistenceException("Couldn't store GDM data into database. Received status code '" + response.getStatus()
+ "' from database endpoint.");
}
}
private de.avgl.dmp.graph.json.Model readGDMFromDB(final String recordClassUri, final String resourceGraphUri) throws DMPPersistenceException {
final WebTarget target = target("/get");
final ObjectMapper objectMapper = DMPPersistenceUtil.getJSONObjectMapper();
final ObjectNode requestJson = objectMapper.createObjectNode();
requestJson.put("record_class_uri", recordClassUri);
requestJson.put("resource_graph_uri", resourceGraphUri);
String requestJsonString;
try {
requestJsonString = objectMapper.writeValueAsString(requestJson);
} catch (final JsonProcessingException e) {
throw new DMPPersistenceException("something went wrong, while creating the request JSON string for the read-gdm-from-db request");
}
// POST the request
final Response response = target.request(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(requestJsonString, MediaType.APPLICATION_JSON));
if (response.getStatus() != 200) {
throw new DMPPersistenceException("Couldn't read GDM data from database. Received status code '" + response.getStatus()
+ "' from database endpoint.");
}
final String body = response.readEntity(String.class);
final ObjectMapper gdmObjectMapper = Util.getJSONObjectMapper();
final de.avgl.dmp.graph.json.Model model;
try {
model = gdmObjectMapper.readValue(body, de.avgl.dmp.graph.json.Model.class);
} catch (final JsonParseException e) {
throw new DMPPersistenceException("something went wrong, while parsing the JSON string");
} catch (final JsonMappingException e) {
throw new DMPPersistenceException("something went wrong, while mapping the JSON string");
} catch (final IOException e) {
throw new DMPPersistenceException("something went wrong, while processing the JSON string");
}
return model;
}
private Client client() {
final ClientBuilder builder = ClientBuilder.newBuilder();
return builder.register(MultiPartFeature.class).build();
}
private WebTarget target() {
return client().target(graphEndpoint).path(InternalGDMGraphService.resourceIdentifier);
}
private WebTarget target(final String... path) {
WebTarget target = target();
for (final String p : path) {
target = target.path(p);
}
return target;
}
}
|
persistence/src/main/java/de/avgl/dmp/persistence/service/internal/graph/InternalGDMGraphService.java
|
package de.avgl.dmp.persistence.service.internal.graph;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import de.avgl.dmp.graph.json.Resource;
import de.avgl.dmp.graph.json.util.Util;
import de.avgl.dmp.persistence.DMPPersistenceException;
import de.avgl.dmp.persistence.model.internal.Model;
import de.avgl.dmp.persistence.model.internal.gdm.GDMModel;
import de.avgl.dmp.persistence.model.internal.helper.AttributePathHelper;
import de.avgl.dmp.persistence.model.proxy.RetrievalType;
import de.avgl.dmp.persistence.model.resource.DataModel;
import de.avgl.dmp.persistence.model.resource.proxy.ProxyDataModel;
import de.avgl.dmp.persistence.model.schema.Attribute;
import de.avgl.dmp.persistence.model.schema.AttributePath;
import de.avgl.dmp.persistence.model.schema.Clasz;
import de.avgl.dmp.persistence.model.schema.Schema;
import de.avgl.dmp.persistence.model.schema.proxy.ProxyAttribute;
import de.avgl.dmp.persistence.model.schema.proxy.ProxyAttributePath;
import de.avgl.dmp.persistence.model.schema.proxy.ProxyClasz;
import de.avgl.dmp.persistence.model.schema.proxy.ProxySchema;
import de.avgl.dmp.persistence.model.schema.utils.SchemaUtils;
import de.avgl.dmp.persistence.service.InternalModelService;
import de.avgl.dmp.persistence.service.resource.DataModelService;
import de.avgl.dmp.persistence.service.schema.AttributePathService;
import de.avgl.dmp.persistence.service.schema.AttributeService;
import de.avgl.dmp.persistence.service.schema.ClaszService;
import de.avgl.dmp.persistence.service.schema.SchemaService;
import de.avgl.dmp.persistence.util.DMPPersistenceUtil;
import de.avgl.dmp.persistence.util.GDMUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A internal model service implementation for RDF triples.<br/>
* Currently, the Neo4j database is utilised.
*
* @author tgaengler
*/
@Singleton
public class InternalGDMGraphService implements InternalModelService {
private static final Logger LOG = LoggerFactory.getLogger(InternalGDMGraphService.class);
private static final String resourceIdentifier = "gdm";
/**
* The data model persistence service.
*/
private final Provider<DataModelService> dataModelService;
/**
* The schema persistence service.
*/
private final Provider<SchemaService> schemaService;
/**
* The class persistence service.
*/
private final Provider<ClaszService> classService;
private final Provider<AttributePathService> attributePathService;
private final Provider<AttributeService> attributeService;
/**
* The data model graph URI pattern
*/
private static final String DATA_MODEL_GRAPH_URI_PATTERN = "http://data.slub-dresden.de/datamodel/{datamodelid}/data";
private final String graphEndpoint;
/**
* /** Creates a new internal triple service with the given data model persistence service, schema persistence service, class
* persistence service and the endpoint to access the graph database.
*
* @param dataModelService the data model persistence service
* @param schemaService the schema persistence service
* @param classService the class persistence service
* @param attributePathService the attribute path persistence service
* @param attributeService the attribute persistence service
* @param graphEndpointArg the endpoint to access the graph database
*/
@Inject
public InternalGDMGraphService(final Provider<DataModelService> dataModelService, final Provider<SchemaService> schemaService,
final Provider<ClaszService> classService, final Provider<AttributePathService> attributePathService,
final Provider<AttributeService> attributeService, @Named("dmp_graph_endpoint") final String graphEndpointArg) {
this.dataModelService = dataModelService;
this.schemaService = schemaService;
this.classService = classService;
this.attributePathService = attributePathService;
this.attributeService = attributeService;
graphEndpoint = graphEndpointArg;
}
/**
* {@inheritDoc}
*/
@Override
public void createObject(final Long dataModelId, final Object model) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
if (model == null) {
throw new DMPPersistenceException("model that should be added to DB shouldn't be null");
}
if (!GDMModel.class.isInstance(model)) {
throw new DMPPersistenceException("this service can only process GDM models");
}
final GDMModel gdmModel = (GDMModel) model;
final de.avgl.dmp.graph.json.Model realModel = gdmModel.getModel();
if (realModel == null) {
throw new DMPPersistenceException("real model that should be added to DB shouldn't be null");
}
final String resourceGraphURI = InternalGDMGraphService.DATA_MODEL_GRAPH_URI_PATTERN.replace("{datamodelid}", dataModelId.toString());
final DataModel dataModel = addRecordClass(dataModelId, gdmModel.getRecordClassURI());
final DataModel finalDataModel;
if (dataModel != null) {
finalDataModel = dataModel;
} else {
finalDataModel = getDataModel(dataModelId);
}
if (finalDataModel.getSchema() != null) {
if (finalDataModel.getSchema().getRecordClass() != null) {
final String recordClassURI = finalDataModel.getSchema().getRecordClass().getUri();
final Set<Resource> recordResources = GDMUtil.getRecordResources(recordClassURI, realModel);
if (recordResources != null) {
final Set<String> recordURIs = Sets.newHashSet();
for (final Resource recordResource : recordResources) {
recordURIs.add(recordResource.getUri());
}
gdmModel.setRecordURIs(recordURIs);
}
}
}
addAttributePaths(finalDataModel, gdmModel.getAttributePaths());
writeGDMToDB(realModel, resourceGraphURI);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Map<String, Model>> getObjects(final Long dataModelId, final Optional<Integer> atMost) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
final String resourceGraphURI = InternalGDMGraphService.DATA_MODEL_GRAPH_URI_PATTERN.replace("{datamodelid}", dataModelId.toString());
// retrieve record class uri from data model schema
final DataModel dataModel = dataModelService.get().getObject(dataModelId);
if (dataModel == null) {
InternalGDMGraphService.LOG.debug("couldn't find data model '" + dataModelId + "' to retrieve record class from");
throw new DMPPersistenceException("couldn't find data model '" + dataModelId + "' to retrieve record class from");
}
final Schema schema = dataModel.getSchema();
if (schema == null) {
InternalGDMGraphService.LOG.debug("couldn't find schema in data model '" + dataModelId + "'");
throw new DMPPersistenceException("couldn't find schema in data model '" + dataModelId + "'");
}
final Clasz recordClass = schema.getRecordClass();
if (recordClass == null) {
InternalGDMGraphService.LOG.debug("couldn't find record class in schema '" + schema.getId() + "' of data model '" + dataModelId + "'");
throw new DMPPersistenceException("couldn't find record class in schema '" + schema.getId() + "' of data model '" + dataModelId + "'");
}
final String recordClassUri = recordClass.getUri();
final de.avgl.dmp.graph.json.Model model = readGDMFromDB(recordClassUri, resourceGraphURI);
if (model == null) {
InternalGDMGraphService.LOG.debug("couldn't find model for data model '" + dataModelId + "' in database");
return Optional.absent();
}
if (model.size() <= 0) {
InternalGDMGraphService.LOG.debug("model is empty for data model '" + dataModelId + "' in database");
return Optional.absent();
}
final Set<Resource> recordResources = GDMUtil.getRecordResources(recordClassUri, model);
if (recordResources == null || recordResources.isEmpty()) {
InternalGDMGraphService.LOG.debug("couldn't find records for record class'" + recordClassUri + "' in data model '" + dataModelId + "'");
throw new DMPPersistenceException("couldn't find records for record class'" + recordClassUri + "' in data model '" + dataModelId + "'");
}
final Map<String, Model> modelMap = Maps.newLinkedHashMap();
int i = 0;
for (final Resource recordResource : recordResources) {
if (atMost.isPresent()) {
if (i >= atMost.get()) {
break;
}
}
final de.avgl.dmp.graph.json.Model recordModel = new de.avgl.dmp.graph.json.Model();
recordModel.addResource(recordResource);
final Model rdfModel = new GDMModel(recordModel, recordResource.getUri());
modelMap.put(recordResource.getUri(), rdfModel);
i++;
}
return Optional.of(modelMap);
}
/**
* {@inheritDoc}
*/
@Override
public void deleteObject(final Long dataModelId) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
final String resourceGraphURI = InternalGDMGraphService.DATA_MODEL_GRAPH_URI_PATTERN.replace("{datamodelid}", dataModelId.toString());
// TODO: delete DataModel object from DB here as well?
// dataset.begin(ReadWrite.WRITE);
// dataset.removeNamedModel(resourceGraphURI);
// dataset.commit();
// dataset.end();
// TODO
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Schema> getSchema(final Long dataModelId) throws DMPPersistenceException {
if (dataModelId == null) {
throw new DMPPersistenceException("data model id shouldn't be null");
}
final DataModel dataModel = dataModelService.get().getObject(dataModelId);
if (dataModel == null) {
InternalGDMGraphService.LOG.debug("couldn't find data model '" + dataModelId + "' to retrieve it's schema");
throw new DMPPersistenceException("couldn't find data model '" + dataModelId + "' to retrieve it's schema");
}
final Schema schema = dataModel.getSchema();
if (schema == null) {
InternalGDMGraphService.LOG.debug("couldn't find schema in data model '" + dataModelId + "'");
return Optional.absent();
}
return Optional.of(schema);
}
/**
* Adds the record class to the schema of the data model.
*
* @param dataModelId the identifier of the data model
* @param recordClassUri the identifier of the record class
* @throws DMPPersistenceException
*/
private DataModel addRecordClass(final Long dataModelId, final String recordClassUri) throws DMPPersistenceException {
// (try) add record class uri to schema
final DataModel dataModel = getSchemaInternal(dataModelId);
final Schema schema = dataModel.getSchema();
final Clasz recordClass;
if (schema.getRecordClass() != null) {
if (schema.getRecordClass().getUri().equals(recordClassUri)) {
// nothing to do, record class is already set
return dataModel;
}
} else {
// create new class
final ProxyClasz proxyRecordClass = classService.get().createOrGetObjectTransactional(recordClassUri);
if (proxyRecordClass == null) {
throw new DMPPersistenceException("couldn't create or retrieve record class");
}
recordClass = proxyRecordClass.getObject();
if (proxyRecordClass.getType().equals(RetrievalType.CREATED)) {
if (recordClass == null) {
throw new DMPPersistenceException("couldn't create new record class");
}
final String recordClassName = SchemaUtils.determineRelativeURIPart(recordClassUri);
recordClass.setName(recordClassName);
}
schema.setRecordClass(recordClass);
}
final ProxyDataModel proxyUpdatedDataModel = dataModelService.get().updateObjectTransactional(dataModel);
if (proxyUpdatedDataModel == null) {
throw new DMPPersistenceException("couldn't update data model");
}
return proxyUpdatedDataModel.getObject();
}
private DataModel addAttributePaths(final DataModel dataModel, final Set<AttributePathHelper> attributePathHelpers)
throws DMPPersistenceException {
if (attributePathHelpers == null) {
InternalGDMGraphService.LOG.debug("couldn't determine attribute paths from data model '" + dataModel.getId() + "'");
return dataModel;
}
if (attributePathHelpers.isEmpty()) {
InternalGDMGraphService.LOG.debug("there are no attribute paths from data model '" + dataModel.getId() + "'");
}
for (final AttributePathHelper attributePathHelper : attributePathHelpers) {
final LinkedList<Attribute> attributes = Lists.newLinkedList();
final LinkedList<String> attributePathFromHelper = attributePathHelper.getAttributePath();
if (attributePathFromHelper.isEmpty()) {
InternalGDMGraphService.LOG.debug("there are no attributes for this attribute path from data model '" + dataModel.getId() + "'");
}
for (final String attributeString : attributePathFromHelper) {
final ProxyAttribute proxyAttribute = attributeService.get().createOrGetObjectTransactional(attributeString);
if (proxyAttribute == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute");
}
final Attribute attribute = proxyAttribute.getObject();
if (attribute == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute");
}
attributes.add(attribute);
final String attributeName = SchemaUtils.determineRelativeURIPart(attributeString);
attribute.setName(attributeName);
}
final ProxyAttributePath proxyAttributePath = attributePathService.get().createOrGetObjectTransactional(attributes);
if (proxyAttributePath == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute path");
}
final AttributePath attributePath = proxyAttributePath.getObject();
if (attributePath == null) {
throw new DMPPersistenceException("couldn't create or retrieve attribute path");
}
dataModel.getSchema().addAttributePath(attributePath);
}
final ProxyDataModel proxyUpdatedDataModel = dataModelService.get().updateObjectTransactional(dataModel);
if (proxyUpdatedDataModel == null) {
throw new DMPPersistenceException("couldn't update data model");
}
return proxyUpdatedDataModel.getObject();
}
private DataModel getSchemaInternal(final Long dataModelId) throws DMPPersistenceException {
final DataModel dataModel = getDataModel(dataModelId);
final Schema schema;
if (dataModel.getSchema() == null) {
// create new schema
final ProxySchema proxySchema = schemaService.get().createObjectTransactional();
if (proxySchema != null) {
schema = proxySchema.getObject();
} else {
schema = null;
}
dataModel.setSchema(schema);
}
return dataModel;
}
private DataModel getDataModel(final Long dataModelId) {
final DataModel dataModel = dataModelService.get().getObject(dataModelId);
if (dataModel == null) {
InternalGDMGraphService.LOG.debug("couldn't find data model '" + dataModelId + "'");
return null;
}
return dataModel;
}
private void writeGDMToDB(final de.avgl.dmp.graph.json.Model model, final String resourceGraphUri) throws DMPPersistenceException {
final WebTarget target = target("/put");
final ObjectMapper objectMapper = Util.getJSONObjectMapper();
byte[] bytes = null;
try {
bytes = objectMapper.writeValueAsBytes(model);
} catch (final JsonProcessingException e) {
throw new DMPPersistenceException("couldn't serialise model to JSON");
}
// Construct a MultiPart with two body parts
final MultiPart multiPart = new MultiPart();
multiPart.bodyPart(bytes, MediaType.APPLICATION_OCTET_STREAM_TYPE).bodyPart(resourceGraphUri, MediaType.TEXT_PLAIN_TYPE);
// POST the request
final Response response = target.request("multipart/mixed").post(Entity.entity(multiPart, "multipart/mixed"));
if (response.getStatus() != 200) {
throw new DMPPersistenceException("Couldn't store GDM data into database. Received status code '" + response.getStatus()
+ "' from database endpoint.");
}
}
private de.avgl.dmp.graph.json.Model readGDMFromDB(final String recordClassUri, final String resourceGraphUri) throws DMPPersistenceException {
final WebTarget target = target("/get");
final ObjectMapper objectMapper = DMPPersistenceUtil.getJSONObjectMapper();
final ObjectNode requestJson = objectMapper.createObjectNode();
requestJson.put("record_class_uri", recordClassUri);
requestJson.put("resource_graph_uri", resourceGraphUri);
String requestJsonString;
try {
requestJsonString = objectMapper.writeValueAsString(requestJson);
} catch (final JsonProcessingException e) {
throw new DMPPersistenceException("something went wrong, while creating the request JSON string for the read-gdm-from-db request");
}
// POST the request
final Response response = target.request(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(requestJsonString, MediaType.APPLICATION_JSON));
if (response.getStatus() != 200) {
throw new DMPPersistenceException("Couldn't read GDM data from database. Received status code '" + response.getStatus()
+ "' from database endpoint.");
}
final String body = response.readEntity(String.class);
final ObjectMapper gdmObjectMapper = Util.getJSONObjectMapper();
final de.avgl.dmp.graph.json.Model model;
try {
model = gdmObjectMapper.readValue(body, de.avgl.dmp.graph.json.Model.class);
} catch (final JsonParseException e) {
throw new DMPPersistenceException("something went wrong, while parsing the JSON string");
} catch (final JsonMappingException e) {
throw new DMPPersistenceException("something went wrong, while mapping the JSON string");
} catch (final IOException e) {
throw new DMPPersistenceException("something went wrong, while processing the JSON string");
}
return model;
}
private Client client() {
final ClientBuilder builder = ClientBuilder.newBuilder();
return builder.register(MultiPartFeature.class).build();
}
private WebTarget target() {
return client().target(graphEndpoint).path(InternalGDMGraphService.resourceIdentifier);
}
private WebTarget target(final String... path) {
WebTarget target = target();
for (final String p : path) {
target = target.path(p);
}
return target;
}
}
|
Merge branch 'builds/unstable' into 'builds/unstable'
sorted saved transformation results
Sorting for saved transformation results as well. I thought we checked this, but apparentely it doesn't work otherwise. Without web folder
|
persistence/src/main/java/de/avgl/dmp/persistence/service/internal/graph/InternalGDMGraphService.java
|
Merge branch 'builds/unstable' into 'builds/unstable'
|
<ide><path>ersistence/src/main/java/de/avgl/dmp/persistence/service/internal/graph/InternalGDMGraphService.java
<ide> package de.avgl.dmp.persistence.service.internal.graph;
<ide>
<ide> import java.io.IOException;
<add>import java.util.LinkedHashSet;
<ide> import java.util.LinkedList;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import de.avgl.dmp.persistence.service.schema.SchemaService;
<ide> import de.avgl.dmp.persistence.util.DMPPersistenceUtil;
<ide> import de.avgl.dmp.persistence.util.GDMUtil;
<add>
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide>
<ide> if (recordResources != null) {
<ide>
<del> final Set<String> recordURIs = Sets.newHashSet();
<add> final LinkedHashSet<String> recordURIs = Sets.newLinkedHashSet();
<ide>
<ide> for (final Resource recordResource : recordResources) {
<ide>
|
|
JavaScript
|
bsd-3-clause
|
0616c17ed1a1566924914cec0014400a224ddfca
| 0 |
CUUATS/bikemoves-server,CUUATS/bikemoves-server,CUUATS/bikemoves-server
|
const Sequelize = require('sequelize'),
geo = require('./geo.js');
// Define models.
var sequelize = new Sequelize(
process.env.POSTGRES_DB,
process.env.POSTGRES_USER,
process.env.POSTGRES_PASSWORD, {
dialect: 'postgres',
host: process.env.POSTGRES_HOST,
port: parseInt(process.env.POSTGRES_PORT),
logging: false
}
),
User = sequelize.define('user', {
deviceUuid: {
type: Sequelize.STRING,
field: 'device_uuid',
allowNull: false
},
platformName: {
type: Sequelize.STRING,
field: 'platform_name'
},
platformVersion: {
type: Sequelize.FLOAT,
field: 'platform_version'
},
gender: {
type: Sequelize.INTEGER
},
age: {
type: Sequelize.INTEGER
},
cyclingExperience: {
type: Sequelize.INTEGER,
field: 'cycling_experience'
}
}, {
classMethods: {
fromMessage: function(msg) {
// Round the version number to at most two decimal places.
var version = (msg.platformVersion) ?
+(Math.round(msg.platformVersion + 'e+2') + 'e-2') : null;
return {
deviceUuid: msg.deviceUuid,
platformName: msg.platformName,
platformVersion: version,
gender: msg.gender,
age: msg.age,
cyclingExperience: msg.cyclingExperience
};
}
},
freezeTableName: true,
indexes: [
{
type: 'UNIQUE',
fields: ['device_uuid']
}
],
underscored: true
}),
Trip = sequelize.define('trip', {
origin: {
type: Sequelize.INTEGER,
field: 'origin_type'
},
destination: {
type: Sequelize.INTEGER,
field: 'destination_type'
},
startTime: {
type: Sequelize.DATE,
field: 'start_time',
allowNull: false
},
endTime: {
type: Sequelize.DATE,
field: 'end_time',
allowNull: false
},
desiredAccuracy: {
type: Sequelize.INTEGER,
field: 'desired_accuracy',
allowNull: false
},
transit: {
type: Sequelize.BOOLEAN
},
geom: {
type: Sequelize.GEOMETRY('LINESTRING', 4326),
allowNull: false
},
debug: {
type: Sequelize.BOOLEAN,
field: 'debug'
},
appVersion: {
type: Sequelize.STRING,
field: 'app_version'
},
matchStatus: {
type: Sequelize.STRING,
field: 'match_status'
},
region: {
type: Sequelize.STRING
}
}, {
classMethods: {
fromMessage: function(msg, userID) {
return {
origin: msg.origin,
destination: msg.destination,
startTime: new Date(msg.startTime.toNumber()),
endTime: new Date(msg.endTime.toNumber()),
desiredAccuracy: msg.desiredAccuracy,
transit: msg.transit,
geom: geo.toGeoJSON(msg.locations),
user_id: userID,
debug: msg.debug,
appVersion: msg.appVersion
};
}
},
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
Point = sequelize.define('point', {
accuracy: {
type: Sequelize.DOUBLE,
allowNull: false
},
altitude: {
type: Sequelize.DOUBLE
},
heading: {
type: Sequelize.DOUBLE
},
moving: {
type: Sequelize.BOOLEAN
},
speed: {
type: Sequelize.DOUBLE
},
time: {
type: Sequelize.DATE,
allowNull: false
},
event: {
type: Sequelize.INTEGER
},
activity: {
type: Sequelize.INTEGER
},
confidence: {
type: Sequelize.INTEGER
},
geom: {
type: Sequelize.GEOMETRY('POINT', 4326),
allowNull: false
}
}, {
classMethods: {
fromTripMessage: function(tripMsg, tripID) {
return tripMsg.locations.map(function(location) {
return {
accuracy: location.accuracy,
altitude: location.altitude,
heading: location.heading,
moving: location.moving,
speed: location.speed,
time: new Date(location.time.toNumber()),
event: (location.event) ? location.event : null,
activity: (location.activity) ? location.activity : null,
confidence: (location.confidence) ? location.confidence : null,
geom: geo.toGeoJSON(location),
trip_id: tripID
};
});
}
},
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
Incident = sequelize.define('incident', {
category : {
type: Sequelize.STRING
},
comment:{
type: Sequelize.TEXT
},
time:{
type: Sequelize.DATE,
allowNull: false
},
geom: {
type: Sequelize.GEOMETRY("POINT", 4326)
}
}, {
classMethods: {
fromMessage: function(msg, userID){
return {
deviceUuid : msg.deviceUuid,
category : msg.category,
comment: msg.comment,
time: new Date(msg.time.toNumber()),
geom: geo.toGeoJSON(msg.location),
user_id: userID
}
}
},
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored:true
}),
RouteLeg = sequelize.define('route_leg', {
matching: {
type: Sequelize.INTEGER,
},
leg: {
type: Sequelize.INTEGER,
},
distance: {
type: Sequelize.DOUBLE,
},
duration: {
type: Sequelize.DOUBLE,
},
speed: {
type: Sequelize.DOUBLE,
},
speedOutlier: {
type: Sequelize.BOOLEAN,
field: 'speed_outlier'
},
routeType: {
type: Sequelize.STRING,
field: 'route_type'
},
nodes: {
type: Sequelize.ARRAY(Sequelize.BIGINT)
},
geom: {
type: Sequelize.GEOMETRY('LINESTRING', 4326),
allowNull: false
}
}, {
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
RouteTracepoint = sequelize.define('route_tracepoint', {
geom: {
type: Sequelize.GEOMETRY('POINT', 4326),
allowNull: false
}
}, {
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
DemographicSummary = sequelize.define('demographic_summary', {
region: {
type: Sequelize.STRING
},
category: {
type: Sequelize.STRING
},
rowOrder: {
type: Sequelize.INTEGER,
field: 'row_order'
},
description: {
type: Sequelize.STRING
},
users: {
type: Sequelize.INTEGER
},
trips: {
type: Sequelize.INTEGER
},
distance: {
type: Sequelize.DOUBLE
}
}, {
freezeTableName: true,
indexes: [
{
fields: ['region']
}
],
underscored: true
});
// Set up foreign keys
Trip.belongsTo(User);
Trip.hasMany(Point);
Incident.belongsTo(User);
RouteLeg.belongsTo(Trip);
RouteLeg.belongsTo(Point, {as: 'startPoint'});
RouteLeg.belongsTo(Point, {as: 'endPoint'});
RouteTracepoint.belongsTo(Trip);
RouteTracepoint.belongsTo(Point);
// Update models.
function prepare(retries) {
if (retries === undefined) retries = 5;
return sequelize.authenticate()
.then(() => sequelize.sync())
.catch(() => {
if (retries === 0) return reject();
console.log('Database unavailable: ' + (retries - 1) + ' more tries');
return new Promise((resolve, reject) => {
setTimeout(() => {
prepare(retries - 1).then(resolve);
}, 3000);
});
});
};
exports.sequelize = sequelize;
exports.User = User;
exports.Trip = Trip;
exports.Point = Point;
exports.Incident = Incident;
exports.RouteLeg = RouteLeg;
exports.RouteTracepoint = RouteTracepoint;
exports.DemographicSummary = DemographicSummary;
exports.prepare = prepare;
|
db.js
|
const Sequelize = require('sequelize'),
geo = require('./geo.js');
// Define models.
var sequelize = new Sequelize(
process.env.POSTGRES_DB,
process.env.POSTGRES_USER,
process.env.POSTGRES_PASSWORD, {
dialect: 'postgres',
host: process.env.POSTGRES_HOST,
port: parseInt(process.env.POSTGRES_PORT),
logging: false
}
),
User = sequelize.define('user', {
deviceUuid: {
type: Sequelize.STRING,
field: 'device_uuid',
allowNull: false
},
platformName: {
type: Sequelize.STRING,
field: 'platform_name'
},
platformVersion: {
type: Sequelize.FLOAT,
field: 'platform_version'
},
gender: {
type: Sequelize.INTEGER
},
age: {
type: Sequelize.INTEGER
},
cyclingExperience: {
type: Sequelize.INTEGER,
field: 'cycling_experience'
}
}, {
classMethods: {
fromMessage: function(msg) {
// Round the version number to at most two decimal places.
var version = (msg.platformVersion) ?
+(Math.round(msg.platformVersion + 'e+2') + 'e-2') : null;
return {
deviceUuid: msg.deviceUuid,
platformName: msg.platformName,
platformVersion: version,
gender: msg.gender,
age: msg.age,
cyclingExperience: msg.cyclingExperience
};
}
},
freezeTableName: true,
indexes: [
{
type: 'UNIQUE',
fields: ['device_uuid']
}
],
underscored: true
}),
Trip = sequelize.define('trip', {
origin: {
type: Sequelize.INTEGER,
field: 'origin_type'
},
destination: {
type: Sequelize.INTEGER,
field: 'destination_type'
},
startTime: {
type: Sequelize.DATE,
field: 'start_time',
allowNull: false
},
endTime: {
type: Sequelize.DATE,
field: 'end_time',
allowNull: false
},
desiredAccuracy: {
type: Sequelize.INTEGER,
field: 'desired_accuracy',
allowNull: false
},
transit: {
type: Sequelize.BOOLEAN
},
geom: {
type: Sequelize.GEOMETRY('LINESTRING', 4326),
allowNull: false
},
debug: {
type: Sequelize.BOOLEAN,
field: 'debug'
},
appVersion: {
type: Sequelize.STRING,
field: 'app_version'
},
matchStatus: {
type: Sequelize.STRING,
field: 'match_status'
},
region: {
type: Sequelize.STRING
}
}, {
classMethods: {
fromMessage: function(msg, userID) {
return {
origin: msg.origin,
destination: msg.destination,
startTime: new Date(msg.startTime.toNumber()),
endTime: new Date(msg.endTime.toNumber()),
desiredAccuracy: msg.desiredAccuracy,
transit: msg.transit,
geom: geo.toGeoJSON(msg.locations),
user_id: userID,
debug: msg.debug,
appVersion: msg.appVersion
};
}
},
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
Point = sequelize.define('point', {
accuracy: {
type: Sequelize.DOUBLE,
allowNull: false
},
altitude: {
type: Sequelize.DOUBLE
},
heading: {
type: Sequelize.DOUBLE
},
moving: {
type: Sequelize.BOOLEAN
},
speed: {
type: Sequelize.DOUBLE
},
time: {
type: Sequelize.DATE,
allowNull: false
},
event: {
type: Sequelize.INTEGER
},
activity: {
type: Sequelize.INTEGER
},
confidence: {
type: Sequelize.INTEGER
},
geom: {
type: Sequelize.GEOMETRY('POINT', 4326),
allowNull: false
}
}, {
classMethods: {
fromTripMessage: function(tripMsg, tripID) {
return tripMsg.locations.map(function(location) {
return {
accuracy: location.accuracy,
altitude: location.altitude,
heading: location.heading,
moving: location.moving,
speed: location.speed,
time: new Date(location.time.toNumber()),
event: (location.event) ? location.event : null,
activity: (location.activity) ? location.activity : null,
confidence: (location.confidence) ? location.confidence : null,
geom: geo.toGeoJSON(location),
trip_id: tripID
};
});
}
},
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
Incident = sequelize.define('incident', {
category : {
type: Sequelize.STRING
},
comment:{
type: Sequelize.TEXT
},
time:{
type: Sequelize.DATE,
allowNull: false
},
geom: {
type: Sequelize.GEOMETRY("POINT", 4326)
}
}, {
classMethods: {
fromMessage: function(msg, userID){
return {
deviceUuid : msg.deviceUuid,
category : msg.category,
comment: msg.comment,
time: new Date(msg.time.toNumber()),
geom: geo.toGeoJSON(msg.location),
user_id: userID
}
}
},
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored:true
}),
RouteLeg = sequelize.define('route_leg', {
matching: {
type: Sequelize.INTEGER,
},
leg: {
type: Sequelize.INTEGER,
},
distance: {
type: Sequelize.DOUBLE,
},
duration: {
type: Sequelize.DOUBLE,
},
speed: {
type: Sequelize.DOUBLE,
},
speedOutlier: {
type: Sequelize.BOOLEAN,
},
routeType: {
type: Sequelize.STRING,
field: 'route_type'
},
nodes: {
type: Sequelize.ARRAY(Sequelize.BIGINT)
},
geom: {
type: Sequelize.GEOMETRY('LINESTRING', 4326),
allowNull: false
}
}, {
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
RouteTracepoint = sequelize.define('route_tracepoint', {
geom: {
type: Sequelize.GEOMETRY('POINT', 4326),
allowNull: false
}
}, {
freezeTableName: true,
indexes: [
{
type: 'SPATIAL',
method: 'GIST',
fields: ['geom']
}
],
underscored: true
}),
DemographicSummary = sequelize.define('demographic_summary', {
region: {
type: Sequelize.STRING
},
category: {
type: Sequelize.STRING
},
rowOrder: {
type: Sequelize.INTEGER,
field: 'row_order'
},
description: {
type: Sequelize.STRING
},
users: {
type: Sequelize.INTEGER
},
trips: {
type: Sequelize.INTEGER
},
distance: {
type: Sequelize.DOUBLE
}
}, {
freezeTableName: true,
indexes: [
{
fields: ['region']
}
],
underscored: true
});
// Set up foreign keys
Trip.belongsTo(User);
Trip.hasMany(Point);
Incident.belongsTo(User);
RouteLeg.belongsTo(Trip);
RouteLeg.belongsTo(Point, {as: 'startPoint'});
RouteLeg.belongsTo(Point, {as: 'endPoint'});
RouteTracepoint.belongsTo(Trip);
RouteTracepoint.belongsTo(Point);
// Update models.
function prepare(retries) {
if (retries === undefined) retries = 5;
return sequelize.authenticate()
.then(() => sequelize.sync())
.catch(() => {
if (retries === 0) return reject();
console.log('Database unavailable: ' + (retries - 1) + ' more tries');
return new Promise((resolve, reject) => {
setTimeout(() => {
prepare(retries - 1).then(resolve);
}, 3000);
});
});
};
exports.sequelize = sequelize;
exports.User = User;
exports.Trip = Trip;
exports.Point = Point;
exports.Incident = Incident;
exports.RouteLeg = RouteLeg;
exports.RouteTracepoint = RouteTracepoint;
exports.DemographicSummary = DemographicSummary;
exports.prepare = prepare;
|
Set speed outlier field name.
|
db.js
|
Set speed outlier field name.
|
<ide><path>b.js
<ide> },
<ide> speedOutlier: {
<ide> type: Sequelize.BOOLEAN,
<add> field: 'speed_outlier'
<ide> },
<ide> routeType: {
<ide> type: Sequelize.STRING,
|
|
Java
|
apache-2.0
|
c9e470b1418a6771539920b9d971beae917b46f7
| 0 |
yihtserns/jaxb-bean-unmarshaller,yihtserns/jaxbean-unmarshaller
|
/*
* Copyright 2015 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.yihtserns.jaxb.bean.unmarshaller;
import java.beans.Introspector;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author yihtserns
*/
public class JaxbBeanUnmarshaller {
private static final String AUTO_GENERATED_NAME = "##default";
private Map<String, Unmarshaller> globalName2Unmarshaller = new HashMap<String, Unmarshaller>();
private Map<Class<?>, String> globalType2Name = new HashMap<Class<?>, String>();
private Map<Class<?>, Unmarshaller> type2Unmarshaller = new HashMap<Class<?>, Unmarshaller>();
private Map<Class<?>, Unmarshaller> type2InitializedUnmarshaller = new HashMap<Class<?>, Unmarshaller>();
/**
* @see #newInstance(java.lang.Class...)
*/
private JaxbBeanUnmarshaller() {
}
public Object unmarshal(Element element) throws Exception {
String globalName = element.getLocalName();
Unmarshaller unmarshaller = globalName2Unmarshaller.get(globalName);
return unmarshaller.unmarshal(element);
}
private void addGlobalType(Class<?> type) throws Exception {
String elementName = resolveRootElementName(type);
Unmarshaller unmarshaller = getUnmarshallerForType(type);
globalName2Unmarshaller.put(elementName, unmarshaller);
globalType2Name.put(type, elementName);
}
private void init() throws Exception {
while (!type2Unmarshaller.isEmpty()) {
Collection<Unmarshaller> toBeInitialized = new ArrayList(type2Unmarshaller.values());
type2InitializedUnmarshaller.putAll(type2Unmarshaller);
type2Unmarshaller.clear();
for (Unmarshaller unmarshaller : toBeInitialized) {
unmarshaller.init();
}
}
}
private Unmarshaller getUnmarshallerForType(Class<?> type) throws NoSuchMethodException {
Unmarshaller unmarshaller = type2InitializedUnmarshaller.get(type);
if (unmarshaller == null) {
unmarshaller = type2Unmarshaller.get(type);
}
if (unmarshaller == null) {
if (type == String.class) {
unmarshaller = new StringUnmarshaller();
} else {
unmarshaller = new BeanUnmarshaller(type.getDeclaredConstructor());
}
type2Unmarshaller.put(type, unmarshaller);
}
return unmarshaller;
}
private Resolver getResolverFor(XmlAccessorType xmlAccessorType) throws UnsupportedOperationException {
switch (xmlAccessorType.value()) {
case FIELD:
return Resolver.FIELD;
case PROPERTY:
return Resolver.METHOD;
default:
throw new UnsupportedOperationException("XML Access Type not supported yet: " + xmlAccessorType.value());
}
}
public static JaxbBeanUnmarshaller newInstance(Class<?>... types) throws Exception {
JaxbBeanUnmarshaller jaxbBeanUnmarshaller = new JaxbBeanUnmarshaller();
for (Class<?> type : types) {
jaxbBeanUnmarshaller.addGlobalType(type);
}
jaxbBeanUnmarshaller.init();
return jaxbBeanUnmarshaller;
}
private static String resolveRootElementName(Class<?> type) {
XmlRootElement xmlRootElement = type.getAnnotation(XmlRootElement.class);
String name = xmlRootElement.name();
if (name.equals(AUTO_GENERATED_NAME)) {
name = Introspector.decapitalize(type.getSimpleName());
}
return name;
}
private interface Unmarshaller {
public Object unmarshal(Element element) throws Exception;
public void init() throws Exception;
}
private class StringUnmarshaller implements Unmarshaller {
public Object unmarshal(Element element) {
return element.getTextContent();
}
public void init() {
}
}
private class WrapperUnmarshaller implements Unmarshaller {
private Map<String, Unmarshaller> localName2Unmarshaller = new HashMap<String, Unmarshaller>();
public Object unmarshal(Element element) throws Exception {
List<Object> result = new ArrayList<Object>();
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if (item.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element childElement = (Element) item;
String localName = childElement.getLocalName();
Unmarshaller unmarshaller = localName2Unmarshaller.get(localName);
if (unmarshaller != null) {
Object instance = unmarshaller.unmarshal(childElement);
result.add(instance);
}
}
return result;
}
public void put(String localName, Unmarshaller unmarshaller) {
this.localName2Unmarshaller.put(localName, unmarshaller);
}
public void init() throws Exception {
}
}
private class BeanUnmarshaller implements Unmarshaller {
Set<String> listTypeElementNames = new HashSet<String>();
Map<String, String> elementName2PropertyName = new HashMap<String, String>();
Map<String, String> attributeName2PropertyName = new HashMap<String, String>();
Map<String, Unmarshaller> localName2Unmarshaller = new HashMap<String, Unmarshaller>();
String textContentPropertyName = null;
final Class<?> beanClass;
Constructor constructor;
private BeanUnmarshaller(Constructor constructor) {
this.beanClass = constructor.getDeclaringClass();
this.constructor = constructor;
}
public Object unmarshal(Element element) throws Exception {
Object instance = newInstance();
BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(instance);
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attr = (Attr) attributes.item(i);
if (isNamespaceDeclaration(attr)) {
continue;
}
String propertyName = resolvePropertyName(attr);
bean.setPropertyValue(propertyName, attr.getValue());
}
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if (item.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element childElement = (Element) item;
String localName = item.getLocalName();
Unmarshaller childUnmarshaller = localName2Unmarshaller.get(localName);
if (childUnmarshaller == null) {
childUnmarshaller = globalName2Unmarshaller.get(localName);
}
Object childInstance = childUnmarshaller.unmarshal(childElement);
String propertyName = resolvePropertyName(childElement);
if (listTypeElementNames.contains(localName)) {
Object valueList = bean.getPropertyValue(propertyName);
if (valueList == null) {
valueList = new ArrayList();
} else if (valueList.getClass().isArray()) {
valueList = new ArrayList(Arrays.asList((Object[]) valueList));
}
((List) valueList).add(childInstance);
childInstance = valueList;
}
bean.setPropertyValue(propertyName, childInstance);
}
if (textContentPropertyName != null) {
bean.setPropertyValue(textContentPropertyName, element.getTextContent());
}
return instance;
}
public <T extends AccessibleObject> void addAttribute(T accObj, Resolver<T> resolver) {
String propertyName = resolver.getPropertyName(accObj);
String attributeName = accObj.getAnnotation(XmlAttribute.class).name();
if (!attributeName.equals(AUTO_GENERATED_NAME)) {
attributeName2PropertyName.put(attributeName, propertyName);
}
}
public <T extends AccessibleObject> void addElement(XmlElement xmlElement, T accObj, Resolver<T> resolver) throws NoSuchMethodException {
String propertyName = resolver.getPropertyName(accObj);
boolean wrapped = accObj.isAnnotationPresent(XmlElementWrapper.class);
String elementName;
if (wrapped) {
elementName = accObj.getAnnotation(XmlElementWrapper.class).name();
} else {
elementName = xmlElement.name();
}
if (elementName.equals(AUTO_GENERATED_NAME)) {
elementName = propertyName;
}
Class<?> type = resolver.getPropertyType(accObj);
if (type == List.class) {
type = resolver.getListComponentType(accObj);
if (!wrapped) {
listTypeElementNames.add(elementName);
}
} else if (type.isArray()) {
type = type.getComponentType();
listTypeElementNames.add(elementName);
}
Class<?> elementType = xmlElement.type();
if (elementType != XmlElement.DEFAULT.class) {
type = elementType;
}
Unmarshaller childUnmarshaller = getUnmarshallerForType(type);
if (wrapped) {
String wrappedElementName = xmlElement.name();
if (wrappedElementName.equals(AUTO_GENERATED_NAME)) {
wrappedElementName = propertyName;
}
WrapperUnmarshaller wrapperUnmarshaller = (WrapperUnmarshaller) localName2Unmarshaller.get(elementName);
if (wrapperUnmarshaller == null) {
wrapperUnmarshaller = new WrapperUnmarshaller();
}
wrapperUnmarshaller.put(wrappedElementName, childUnmarshaller);
childUnmarshaller = wrapperUnmarshaller;
}
if (!elementName.equals(propertyName)) {
elementName2PropertyName.put(elementName, propertyName);
}
localName2Unmarshaller.put(elementName, childUnmarshaller);
}
public <T extends AccessibleObject> void addElementRef(T accObj, Resolver<T> resolver) {
Class<?> propertyType = resolver.getPropertyType(accObj);
String propertyName = resolver.getPropertyName(accObj);
boolean isListType = (propertyType == List.class);
if (isListType) {
propertyType = resolver.getListComponentType(accObj);
}
for (Entry<Class<?>, String> entry : globalType2Name.entrySet()) {
Class<?> globalType = entry.getKey();
if (propertyType.isAssignableFrom(globalType)) {
String globalName = entry.getValue();
elementName2PropertyName.put(globalName, propertyName);
if (isListType) {
listTypeElementNames.add(globalName);
}
}
}
}
private <T extends AccessibleObject> void setTextContent(T accObj, Resolver<T> resolver) {
this.textContentPropertyName = resolver.getPropertyName(accObj);
}
public void init() throws Exception {
Class<?> currentClass = beanClass;
while (currentClass != Object.class) {
XmlAccessorType xmlAccessorType = currentClass.getAnnotation(XmlAccessorType.class);
Resolver resolver = getResolverFor(xmlAccessorType);
for (AccessibleObject accObj : resolver.getDirectMembers(currentClass)) {
if (accObj.isAnnotationPresent(XmlAttribute.class)) {
addAttribute(accObj, resolver);
} else if (accObj.isAnnotationPresent(XmlElement.class)) {
XmlElement xmlElement = accObj.getAnnotation(XmlElement.class);
addElement(xmlElement, accObj, resolver);
} else if (accObj.isAnnotationPresent(XmlElements.class)) {
XmlElements xmlElements = accObj.getAnnotation(XmlElements.class);
for (XmlElement xmlElement : xmlElements.value()) {
addElement(xmlElement, accObj, resolver);
}
} else if (accObj.isAnnotationPresent(XmlElementRef.class)) {
addElementRef(accObj, resolver);
} else if (accObj.isAnnotationPresent(XmlValue.class)) {
setTextContent(accObj, resolver);
}
}
currentClass = currentClass.getSuperclass();
}
}
private boolean isNamespaceDeclaration(Attr attr) {
String fullName = attr.getName();
return fullName.equals("xmlns") || fullName.startsWith("xmlns:");
}
private Object newInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
boolean originalAccessibility = constructor.isAccessible();
try {
constructor.setAccessible(true);
return constructor.newInstance();
} finally {
constructor.setAccessible(originalAccessibility);
}
}
private String resolvePropertyName(Attr attribute) {
String attributeName = attribute.getName();
String propertyName = attributeName2PropertyName.get(attributeName);
return propertyName != null ? propertyName : attributeName;
}
private String resolvePropertyName(Element element) {
String elementName = element.getLocalName();
String propertyName = elementName2PropertyName.get(elementName);
return propertyName != null ? propertyName : elementName;
}
}
private static abstract class Resolver<T extends AccessibleObject> {
public static final Resolver<Method> METHOD = new Resolver<Method>() {
@Override
public AccessibleObject[] getDirectMembers(Class<?> type) {
return type.getDeclaredMethods();
}
public String getPropertyName(Method method) {
String propertyName = method.getName();
if (propertyName.startsWith("is")) {
propertyName = propertyName.substring(2);
} else {
// Assume is setXXX/getXXX
propertyName = propertyName.substring(3);
}
return Introspector.decapitalize(propertyName);
}
public Class<?> getPropertyType(Method method) {
return isSetter(method) ? method.getParameterTypes()[0] : method.getReturnType();
}
@Override
public Type getGenericType(Method method) {
return isSetter(method) ? method.getGenericParameterTypes()[0] : method.getGenericReturnType();
}
private boolean isSetter(Method method) {
return method.getName().startsWith("set");
}
};
private static final Resolver<Field> FIELD = new Resolver<Field>() {
@Override
public AccessibleObject[] getDirectMembers(Class<?> type) {
return type.getDeclaredFields();
}
public String getPropertyName(Field field) {
return field.getName();
}
public Class<?> getPropertyType(Field field) {
return field.getType();
}
@Override
public Type getGenericType(Field field) {
return field.getGenericType();
}
};
public abstract AccessibleObject[] getDirectMembers(Class<?> type);
public abstract String getPropertyName(T t);
public abstract Class<?> getPropertyType(T t);
public abstract Type getGenericType(T t);
public Class<?> getListComponentType(T t) {
Type type = getGenericType(t);
type = ((ParameterizedType) type).getActualTypeArguments()[0];
if (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
return (Class) type;
}
}
}
|
src/main/java/com/github/yihtserns/jaxb/bean/unmarshaller/JaxbBeanUnmarshaller.java
|
/*
* Copyright 2015 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.yihtserns.jaxb.bean.unmarshaller;
import java.beans.Introspector;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
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.Map.Entry;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author yihtserns
*/
public class JaxbBeanUnmarshaller {
private static final String AUTO_GENERATED_NAME = "##default";
private Map<String, Unmarshaller> globalName2Unmarshaller = new HashMap<String, Unmarshaller>();
private Map<Class<?>, String> globalType2Name = new HashMap<Class<?>, String>();
private Map<Class<?>, Unmarshaller> type2Unmarshaller = new HashMap<Class<?>, Unmarshaller>();
private Map<Class<?>, Unmarshaller> type2InitializedUnmarshaller = new HashMap<Class<?>, Unmarshaller>();
/**
* @see #newInstance(java.lang.Class...)
*/
private JaxbBeanUnmarshaller() {
}
public Object unmarshal(Element element) throws Exception {
String globalName = element.getLocalName();
Unmarshaller unmarshaller = globalName2Unmarshaller.get(globalName);
return unmarshaller.unmarshal(element);
}
private void addGlobalType(Class<?> type) throws Exception {
String elementName = resolveRootElementName(type);
Unmarshaller unmarshaller = getUnmarshallerForType(type);
globalName2Unmarshaller.put(elementName, unmarshaller);
globalType2Name.put(type, elementName);
}
private void init() throws Exception {
while (!type2Unmarshaller.isEmpty()) {
type2InitializedUnmarshaller.putAll(type2Unmarshaller);
type2Unmarshaller.clear();
for (Unmarshaller unmarshaller : type2InitializedUnmarshaller.values()) {
unmarshaller.init();
}
}
}
private Unmarshaller getUnmarshallerForType(Class<?> type) throws NoSuchMethodException {
Unmarshaller unmarshaller = type2InitializedUnmarshaller.get(type);
if (unmarshaller == null) {
unmarshaller = type2Unmarshaller.get(type);
}
if (unmarshaller == null) {
if (type == String.class) {
unmarshaller = new StringUnmarshaller();
} else {
unmarshaller = new BeanUnmarshaller(type.getDeclaredConstructor());
}
type2Unmarshaller.put(type, unmarshaller);
}
return unmarshaller;
}
private Resolver getResolverFor(XmlAccessorType xmlAccessorType) throws UnsupportedOperationException {
switch (xmlAccessorType.value()) {
case FIELD:
return Resolver.FIELD;
case PROPERTY:
return Resolver.METHOD;
default:
throw new UnsupportedOperationException("XML Access Type not supported yet: " + xmlAccessorType.value());
}
}
public static JaxbBeanUnmarshaller newInstance(Class<?>... types) throws Exception {
JaxbBeanUnmarshaller jaxbBeanUnmarshaller = new JaxbBeanUnmarshaller();
for (Class<?> type : types) {
jaxbBeanUnmarshaller.addGlobalType(type);
}
jaxbBeanUnmarshaller.init();
return jaxbBeanUnmarshaller;
}
private static String resolveRootElementName(Class<?> type) {
XmlRootElement xmlRootElement = type.getAnnotation(XmlRootElement.class);
String name = xmlRootElement.name();
if (name.equals(AUTO_GENERATED_NAME)) {
name = Introspector.decapitalize(type.getSimpleName());
}
return name;
}
private interface Unmarshaller {
public Object unmarshal(Element element) throws Exception;
public void init() throws Exception;
}
private class StringUnmarshaller implements Unmarshaller {
public Object unmarshal(Element element) {
return element.getTextContent();
}
public void init() {
}
}
private class WrapperUnmarshaller implements Unmarshaller {
private Map<String, Unmarshaller> localName2Unmarshaller = new HashMap<String, Unmarshaller>();
public Object unmarshal(Element element) throws Exception {
List<Object> result = new ArrayList<Object>();
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if (item.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element childElement = (Element) item;
String localName = childElement.getLocalName();
Unmarshaller unmarshaller = localName2Unmarshaller.get(localName);
if (unmarshaller != null) {
Object instance = unmarshaller.unmarshal(childElement);
result.add(instance);
}
}
return result;
}
public void put(String localName, Unmarshaller unmarshaller) {
this.localName2Unmarshaller.put(localName, unmarshaller);
}
public void init() throws Exception {
}
}
private class BeanUnmarshaller implements Unmarshaller {
Set<String> listTypeElementNames = new HashSet<String>();
Map<String, String> elementName2PropertyName = new HashMap<String, String>();
Map<String, String> attributeName2PropertyName = new HashMap<String, String>();
Map<String, Unmarshaller> localName2Unmarshaller = new HashMap<String, Unmarshaller>();
String textContentPropertyName = null;
final Class<?> beanClass;
Constructor constructor;
private BeanUnmarshaller(Constructor constructor) {
this.beanClass = constructor.getDeclaringClass();
this.constructor = constructor;
}
public Object unmarshal(Element element) throws Exception {
Object instance = newInstance();
BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(instance);
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attr = (Attr) attributes.item(i);
if (isNamespaceDeclaration(attr)) {
continue;
}
String propertyName = resolvePropertyName(attr);
bean.setPropertyValue(propertyName, attr.getValue());
}
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if (item.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element childElement = (Element) item;
String localName = item.getLocalName();
Unmarshaller childUnmarshaller = localName2Unmarshaller.get(localName);
if (childUnmarshaller == null) {
childUnmarshaller = globalName2Unmarshaller.get(localName);
}
Object childInstance = childUnmarshaller.unmarshal(childElement);
String propertyName = resolvePropertyName(childElement);
if (listTypeElementNames.contains(localName)) {
Object valueList = bean.getPropertyValue(propertyName);
if (valueList == null) {
valueList = new ArrayList();
} else if (valueList.getClass().isArray()) {
valueList = new ArrayList(Arrays.asList((Object[]) valueList));
}
((List) valueList).add(childInstance);
childInstance = valueList;
}
bean.setPropertyValue(propertyName, childInstance);
}
if (textContentPropertyName != null) {
bean.setPropertyValue(textContentPropertyName, element.getTextContent());
}
return instance;
}
public <T extends AccessibleObject> void addAttribute(T accObj, Resolver<T> resolver) {
String propertyName = resolver.getPropertyName(accObj);
String attributeName = accObj.getAnnotation(XmlAttribute.class).name();
if (!attributeName.equals(AUTO_GENERATED_NAME)) {
attributeName2PropertyName.put(attributeName, propertyName);
}
}
public <T extends AccessibleObject> void addElement(XmlElement xmlElement, T accObj, Resolver<T> resolver) throws NoSuchMethodException {
String propertyName = resolver.getPropertyName(accObj);
boolean wrapped = accObj.isAnnotationPresent(XmlElementWrapper.class);
String elementName;
if (wrapped) {
elementName = accObj.getAnnotation(XmlElementWrapper.class).name();
} else {
elementName = xmlElement.name();
}
if (elementName.equals(AUTO_GENERATED_NAME)) {
elementName = propertyName;
}
Class<?> type = resolver.getPropertyType(accObj);
if (type == List.class) {
type = resolver.getListComponentType(accObj);
if (!wrapped) {
listTypeElementNames.add(elementName);
}
} else if (type.isArray()) {
type = type.getComponentType();
listTypeElementNames.add(elementName);
}
Class<?> elementType = xmlElement.type();
if (elementType != XmlElement.DEFAULT.class) {
type = elementType;
}
Unmarshaller childUnmarshaller = getUnmarshallerForType(type);
if (wrapped) {
String wrappedElementName = xmlElement.name();
if (wrappedElementName.equals(AUTO_GENERATED_NAME)) {
wrappedElementName = propertyName;
}
WrapperUnmarshaller wrapperUnmarshaller = (WrapperUnmarshaller) localName2Unmarshaller.get(elementName);
if (wrapperUnmarshaller == null) {
wrapperUnmarshaller = new WrapperUnmarshaller();
}
wrapperUnmarshaller.put(wrappedElementName, childUnmarshaller);
childUnmarshaller = wrapperUnmarshaller;
}
if (!elementName.equals(propertyName)) {
elementName2PropertyName.put(elementName, propertyName);
}
localName2Unmarshaller.put(elementName, childUnmarshaller);
}
public <T extends AccessibleObject> void addElementRef(T accObj, Resolver<T> resolver) {
Class<?> propertyType = resolver.getPropertyType(accObj);
String propertyName = resolver.getPropertyName(accObj);
boolean isListType = (propertyType == List.class);
if (isListType) {
propertyType = resolver.getListComponentType(accObj);
}
for (Entry<Class<?>, String> entry : globalType2Name.entrySet()) {
Class<?> globalType = entry.getKey();
if (propertyType.isAssignableFrom(globalType)) {
String globalName = entry.getValue();
elementName2PropertyName.put(globalName, propertyName);
if (isListType) {
listTypeElementNames.add(globalName);
}
}
}
}
private <T extends AccessibleObject> void setTextContent(T accObj, Resolver<T> resolver) {
this.textContentPropertyName = resolver.getPropertyName(accObj);
}
public void init() throws Exception {
Class<?> currentClass = beanClass;
while (currentClass != Object.class) {
XmlAccessorType xmlAccessorType = currentClass.getAnnotation(XmlAccessorType.class);
Resolver resolver = getResolverFor(xmlAccessorType);
for (AccessibleObject accObj : resolver.getDirectMembers(currentClass)) {
if (accObj.isAnnotationPresent(XmlAttribute.class)) {
addAttribute(accObj, resolver);
} else if (accObj.isAnnotationPresent(XmlElement.class)) {
XmlElement xmlElement = accObj.getAnnotation(XmlElement.class);
addElement(xmlElement, accObj, resolver);
} else if (accObj.isAnnotationPresent(XmlElements.class)) {
XmlElements xmlElements = accObj.getAnnotation(XmlElements.class);
for (XmlElement xmlElement : xmlElements.value()) {
addElement(xmlElement, accObj, resolver);
}
} else if (accObj.isAnnotationPresent(XmlElementRef.class)) {
addElementRef(accObj, resolver);
} else if (accObj.isAnnotationPresent(XmlValue.class)) {
setTextContent(accObj, resolver);
}
}
currentClass = currentClass.getSuperclass();
}
}
private boolean isNamespaceDeclaration(Attr attr) {
String fullName = attr.getName();
return fullName.equals("xmlns") || fullName.startsWith("xmlns:");
}
private Object newInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
boolean originalAccessibility = constructor.isAccessible();
try {
constructor.setAccessible(true);
return constructor.newInstance();
} finally {
constructor.setAccessible(originalAccessibility);
}
}
private String resolvePropertyName(Attr attribute) {
String attributeName = attribute.getName();
String propertyName = attributeName2PropertyName.get(attributeName);
return propertyName != null ? propertyName : attributeName;
}
private String resolvePropertyName(Element element) {
String elementName = element.getLocalName();
String propertyName = elementName2PropertyName.get(elementName);
return propertyName != null ? propertyName : elementName;
}
}
private static abstract class Resolver<T extends AccessibleObject> {
public static final Resolver<Method> METHOD = new Resolver<Method>() {
@Override
public AccessibleObject[] getDirectMembers(Class<?> type) {
return type.getDeclaredMethods();
}
public String getPropertyName(Method method) {
String propertyName = method.getName();
if (propertyName.startsWith("is")) {
propertyName = propertyName.substring(2);
} else {
// Assume is setXXX/getXXX
propertyName = propertyName.substring(3);
}
return Introspector.decapitalize(propertyName);
}
public Class<?> getPropertyType(Method method) {
return isSetter(method) ? method.getParameterTypes()[0] : method.getReturnType();
}
@Override
public Type getGenericType(Method method) {
return isSetter(method) ? method.getGenericParameterTypes()[0] : method.getGenericReturnType();
}
private boolean isSetter(Method method) {
return method.getName().startsWith("set");
}
};
private static final Resolver<Field> FIELD = new Resolver<Field>() {
@Override
public AccessibleObject[] getDirectMembers(Class<?> type) {
return type.getDeclaredFields();
}
public String getPropertyName(Field field) {
return field.getName();
}
public Class<?> getPropertyType(Field field) {
return field.getType();
}
@Override
public Type getGenericType(Field field) {
return field.getGenericType();
}
};
public abstract AccessibleObject[] getDirectMembers(Class<?> type);
public abstract String getPropertyName(T t);
public abstract Class<?> getPropertyType(T t);
public abstract Type getGenericType(T t);
public Class<?> getListComponentType(T t) {
Type type = getGenericType(t);
type = ((ParameterizedType) type).getActualTypeArguments()[0];
if (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
return (Class) type;
}
}
}
|
Stop initializing same unmarshaller multiple times.
|
src/main/java/com/github/yihtserns/jaxb/bean/unmarshaller/JaxbBeanUnmarshaller.java
|
Stop initializing same unmarshaller multiple times.
|
<ide><path>rc/main/java/com/github/yihtserns/jaxb/bean/unmarshaller/JaxbBeanUnmarshaller.java
<ide> import java.lang.reflect.Type;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<add>import java.util.Collection;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide>
<ide> private void init() throws Exception {
<ide> while (!type2Unmarshaller.isEmpty()) {
<add> Collection<Unmarshaller> toBeInitialized = new ArrayList(type2Unmarshaller.values());
<ide> type2InitializedUnmarshaller.putAll(type2Unmarshaller);
<ide> type2Unmarshaller.clear();
<ide>
<del> for (Unmarshaller unmarshaller : type2InitializedUnmarshaller.values()) {
<add> for (Unmarshaller unmarshaller : toBeInitialized) {
<ide> unmarshaller.init();
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
ebc402a14ba4043f32ea81247bec924a1775165d
| 0 |
wcm-io-qa/wcm-io-qa-galenium,wcm-io-qa/wcm-io-qa-galenium,wcm-io-qa/wcm-io-qa-galenium
|
/*
* #%L
* wcm.io
* %%
* Copyright (C) 2018 wcm.io
* %%
* 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.
* #L%
*/
package io.wcm.qa.galenium.interaction;
import static io.wcm.qa.galenium.reporting.GaleniumReportUtil.MARKER_FAIL;
import static io.wcm.qa.galenium.reporting.GaleniumReportUtil.MARKER_INFO;
import static io.wcm.qa.galenium.reporting.GaleniumReportUtil.MARKER_PASS;
import static io.wcm.qa.galenium.util.GaleniumContext.getDriver;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.Marker;
import io.wcm.qa.galenium.exceptions.GaleniumException;
import io.wcm.qa.galenium.reporting.GaleniumReportUtil;
import io.wcm.qa.galenium.selectors.base.Selector;
public final class Element {
private static final Marker MARKER = GaleniumReportUtil.getMarker("galenium.interaction.element");
private Element() {
// do not instantiate
}
/**
* Click element.
* @param selector identifies the element
*/
public static void click(Selector selector) {
WebElement element = findOrFail(selector);
element.click();
getLogger().info(MARKER_PASS, "clicked '" + selector.elementName() + "'");
}
/**
* Click element.
* @param selector identifies the elements to be checked for partial text
* @param searchStr string to be found as part of text of element
*/
public static void clickByPartialText(Selector selector, String searchStr) {
getLogger().debug("looking for pattern: " + searchStr);
WebElement element = findByPartialText(selector, searchStr);
if (element != null) {
getLogger().info("clicked: " + element + " (found by " + selector.elementName() + " with string '" + searchStr + "')");
element.click();
}
else {
getLogger().debug("did not find anything for: " + searchStr + " AND " + selector.elementName());
}
}
/**
* Click first element only even if many are found.
* @param selector identifies the element
*/
public static void clickFirstVisibleOfMany(Selector selector) {
List<WebElement> elements = findAll(selector);
for (WebElement element : elements) {
getLogger().debug("found element with " + selector.elementName() + ": " + element);
if (element.isDisplayed()) {
getLogger().info(MARKER_PASS, "clicking element: " + element);
element.click();
return;
}
}
}
/**
* Click element only if it is visible and don't fail if element cannot be found.
* @param selector identifies the element
*/
public static void clickIfVisible(Selector selector) {
WebElement element = find(selector, 30);
if (element != null) {
element.click();
getLogger().info(MARKER_PASS, "clicked optional '" + selector.elementName() + "'");
}
else {
getLogger().debug("did not click optional '" + selector.elementName() + "'");
}
}
/**
* Enters text into element which replaces any text that might already be in element.
* @param selector identifies the element
* @param text value to enter
*/
public static void enterText(Selector selector, String text) {
WebElement input = findOrFail(selector);
input.clear();
input.sendKeys(text);
}
/**
* @param selector used to find element
* @return matching element if it is visible or null
*/
public static WebElement find(Selector selector) {
return find(selector, 10);
}
/**
* @param selector used to find element
* @param howLong how long to wait for element to be visible in seconds
* @return matching element if it is visible or null
*/
public static WebElement find(Selector selector, int howLong) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(getDriver(), howLong);
try {
element = wait.until(ExpectedConditions.visibilityOfElementLocated(selector.asBy()));
}
catch (TimeoutException tex) {
getLogger().trace("timeout when waiting for: " + selector.elementName());
}
return element;
}
/**
* @param selector used to find elements
* @return list of elements matched by selector
*/
public static List<WebElement> findAll(Selector selector) {
return getDriver().findElements(selector.asBy());
}
/**
* Find elements by partial text.
* @param selector used to find elements
* @param searchStr used to filter elements that contain this text
* @return matching element if it is visible or null
*/
public static WebElement findByPartialText(Selector selector, String searchStr) {
List<WebElement> elements = findAll(selector);
for (WebElement element : elements) {
String text = element.getText();
if (StringUtils.containsIgnoreCase(text, searchStr)) {
return element;
}
}
return null;
}
/**
* Will return immediately whether element is found or not.
* @param selector used to find element
* @return matching element if it is visible or null
*/
public static WebElement findNow(Selector selector) {
return find(selector, 0);
}
/**
* Return element or fail with {@link GaleniumException}.
* @param selector identifies the element
* @return element found
*/
public static WebElement findOrFail(Selector selector) {
return findOrFail(selector, 10);
}
/**
* Return element or fail with {@link GaleniumException}.
* @param selector identifies the element
* @param howLong seconds to try until failure
* @return element found
*/
public static WebElement findOrFail(Selector selector, int howLong) {
WebElement element = find(selector, howLong);
if (element == null) {
String msg = "could not find '" + selector.elementName() + "'";
getLogger().debug(MARKER_FAIL, msg);
throw new GaleniumException(msg);
}
return element;
}
/**
* Return element or fail with {@link GaleniumException} immediately.
* @param selector identifies the element
* @return element found
*/
public static WebElement findOrFailNow(Selector selector) {
return findOrFail(selector, 0);
}
/**
* Checks whether element attribute value equals string argument.
* @param selector identifies element
* @param name attribute to check
* @param value value to compare against
* @return whether element with attribute exists and attribute string representation is equal to value.
*/
public static boolean hasAttribute(Selector selector, String name, String value) {
WebElement element = find(selector);
if (element == null) {
return false;
}
return StringUtils.equals(value, element.getAttribute(name));
}
/**
* Checks for CSS class on element.
* @param selector identifies element
* @param cssClass css class to check for
* @return whether element has a CSS class equal to the value passed
*/
public static boolean hasCssClass(Selector selector, String cssClass) {
WebElement element = find(selector);
if (element == null) {
return false;
}
String[] split = element.getAttribute("class").split(" ");
return ArrayUtils.contains(split, cssClass);
}
public static boolean isVisible(Selector selector) {
return find(selector) != null;
}
/**
* Scroll element into view.
* @param selector identifies element
*/
public static void scrollTo(Selector selector) {
getLogger().debug(MARKER_INFO, "Scrolling to element: '" + selector + "'");
WebElement elementToScrollTo = getDriver().findElement(selector.asBy());
scrollTo(elementToScrollTo);
}
/**
* Scroll element into view.
* @param elementToScrollTo element to scroll to
*/
public static void scrollTo(WebElement elementToScrollTo) {
Actions actions = new Actions(getDriver());
actions.moveToElement(elementToScrollTo);
actions.perform();
}
private static Logger getLogger() {
return GaleniumReportUtil.getMarkedLogger(MARKER);
}
}
|
modules/interaction/src/main/java/io/wcm/qa/galenium/interaction/Element.java
|
/*
* #%L
* wcm.io
* %%
* Copyright (C) 2018 wcm.io
* %%
* 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.
* #L%
*/
package io.wcm.qa.galenium.interaction;
import static io.wcm.qa.galenium.reporting.GaleniumReportUtil.MARKER_FAIL;
import static io.wcm.qa.galenium.reporting.GaleniumReportUtil.MARKER_INFO;
import static io.wcm.qa.galenium.reporting.GaleniumReportUtil.MARKER_PASS;
import static io.wcm.qa.galenium.util.GaleniumContext.getDriver;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.Marker;
import io.wcm.qa.galenium.exceptions.GaleniumException;
import io.wcm.qa.galenium.reporting.GaleniumReportUtil;
import io.wcm.qa.galenium.selectors.base.Selector;
public final class Element {
private static final Marker MARKER = GaleniumReportUtil.getMarker("galenium.interaction.element");
private Element() {
// do not instantiate
}
/**
* Click element.
* @param selector identifies the element
*/
public static void click(Selector selector) {
WebElement element = findOrFail(selector);
element.click();
getLogger().debug(MARKER_PASS, "clicked '" + selector.elementName() + "'");
}
/**
* Click element.
* @param selector identifies the elements to be checked for partial text
* @param searchStr string to be found as part of text of element
*/
public static void clickByPartialText(Selector selector, String searchStr) {
getLogger().debug("looking for pattern: " + searchStr);
WebElement element = findByPartialText(selector, searchStr);
if (element != null) {
getLogger().debug("clicked: " + element + " (found by " + selector.elementName() + " with string '" + searchStr + "')");
element.click();
}
else {
getLogger().debug("did not find anything for: " + searchStr + " AND " + selector.elementName());
}
}
/**
* Click first element only even if many are found.
* @param selector identifies the element
*/
public static void clickFirstVisibleOfMany(Selector selector) {
List<WebElement> elements = findAll(selector);
for (WebElement element : elements) {
getLogger().debug("found element with " + selector.elementName() + ": " + element);
if (element.isDisplayed()) {
getLogger().debug("clicking element: " + element);
element.click();
return;
}
}
}
/**
* Click element only if it is visible and don't fail if element cannot be found.
* @param selector identifies the element
*/
public static void clickIfVisible(Selector selector) {
WebElement element = find(selector, 30);
if (element != null) {
element.click();
getLogger().debug(MARKER_PASS, "clicked optional '" + selector.elementName() + "'");
}
else {
getLogger().debug("did not click optional '" + selector.elementName() + "'");
}
}
/**
* Enters text into element which replaces any text that might already be in element.
* @param selector identifies the element
* @param text value to enter
*/
public static void enterText(Selector selector, String text) {
WebElement input = findOrFail(selector);
input.clear();
input.sendKeys(text);
}
/**
* @param selector used to find element
* @return matching element if it is visible or null
*/
public static WebElement find(Selector selector) {
return find(selector, 10);
}
/**
* @param selector used to find element
* @param howLong how long to wait for element to be visible in seconds
* @return matching element if it is visible or null
*/
public static WebElement find(Selector selector, int howLong) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(getDriver(), howLong);
try {
element = wait.until(ExpectedConditions.visibilityOfElementLocated(selector.asBy()));
}
catch (TimeoutException tex) {
getLogger().trace("timeout when waiting for: " + selector.elementName());
}
return element;
}
/**
* @param selector used to find elements
* @return list of elements matched by selector
*/
public static List<WebElement> findAll(Selector selector) {
return getDriver().findElements(selector.asBy());
}
/**
* Find elements by partial text.
* @param selector used to find elements
* @param searchStr used to filter elements that contain this text
* @return matching element if it is visible or null
*/
public static WebElement findByPartialText(Selector selector, String searchStr) {
List<WebElement> elements = findAll(selector);
for (WebElement element : elements) {
String text = element.getText();
if (StringUtils.containsIgnoreCase(text, searchStr)) {
return element;
}
}
return null;
}
/**
* Will return immediately whether element is found or not.
* @param selector used to find element
* @return matching element if it is visible or null
*/
public static WebElement findNow(Selector selector) {
return find(selector, 0);
}
/**
* Return element or fail with {@link GaleniumException}.
* @param selector identifies the element
* @return element found
*/
public static WebElement findOrFail(Selector selector) {
return findOrFail(selector, 10);
}
/**
* Return element or fail with {@link GaleniumException}.
* @param selector identifies the element
* @param howLong seconds to try until failure
* @return element found
*/
public static WebElement findOrFail(Selector selector, int howLong) {
WebElement element = find(selector, howLong);
if (element == null) {
String msg = "could not find '" + selector.elementName() + "'";
getLogger().debug(MARKER_FAIL, msg);
throw new GaleniumException(msg);
}
return element;
}
/**
* Return element or fail with {@link GaleniumException} immediately.
* @param selector identifies the element
* @return element found
*/
public static WebElement findOrFailNow(Selector selector) {
return findOrFail(selector, 0);
}
/**
* Checks whether element attribute value equals string argument.
* @param selector identifies element
* @param name attribute to check
* @param value value to compare against
* @return whether element with attribute exists and attribute string representation is equal to value.
*/
public static boolean hasAttribute(Selector selector, String name, String value) {
WebElement element = find(selector);
if (element == null) {
return false;
}
return StringUtils.equals(value, element.getAttribute(name));
}
/**
* Checks for CSS class on element.
* @param selector identifies element
* @param cssClass css class to check for
* @return whether element has a CSS class equal to the value passed
*/
public static boolean hasCssClass(Selector selector, String cssClass) {
WebElement element = find(selector);
if (element == null) {
return false;
}
String[] split = element.getAttribute("class").split(" ");
return ArrayUtils.contains(split, cssClass);
}
public static boolean isVisible(Selector selector) {
return find(selector) != null;
}
/**
* Scroll element into view.
* @param selector identifies element
*/
public static void scrollTo(Selector selector) {
getLogger().debug(MARKER_INFO, "Scrolling to element: '" + selector + "'");
WebElement elementToScrollTo = getDriver().findElement(selector.asBy());
scrollTo(elementToScrollTo);
}
/**
* Scroll element into view.
* @param elementToScrollTo element to scroll to
*/
public static void scrollTo(WebElement elementToScrollTo) {
Actions actions = new Actions(getDriver());
actions.moveToElement(elementToScrollTo);
actions.perform();
}
private static Logger getLogger() {
return GaleniumReportUtil.getMarkedLogger(MARKER);
}
}
|
elevate important interactions to INFO level
|
modules/interaction/src/main/java/io/wcm/qa/galenium/interaction/Element.java
|
elevate important interactions to INFO level
|
<ide><path>odules/interaction/src/main/java/io/wcm/qa/galenium/interaction/Element.java
<ide> public static void click(Selector selector) {
<ide> WebElement element = findOrFail(selector);
<ide> element.click();
<del> getLogger().debug(MARKER_PASS, "clicked '" + selector.elementName() + "'");
<add> getLogger().info(MARKER_PASS, "clicked '" + selector.elementName() + "'");
<ide> }
<ide>
<ide> /**
<ide> getLogger().debug("looking for pattern: " + searchStr);
<ide> WebElement element = findByPartialText(selector, searchStr);
<ide> if (element != null) {
<del> getLogger().debug("clicked: " + element + " (found by " + selector.elementName() + " with string '" + searchStr + "')");
<add> getLogger().info("clicked: " + element + " (found by " + selector.elementName() + " with string '" + searchStr + "')");
<ide> element.click();
<ide> }
<ide> else {
<ide> for (WebElement element : elements) {
<ide> getLogger().debug("found element with " + selector.elementName() + ": " + element);
<ide> if (element.isDisplayed()) {
<del> getLogger().debug("clicking element: " + element);
<add> getLogger().info(MARKER_PASS, "clicking element: " + element);
<ide> element.click();
<ide> return;
<ide> }
<ide> WebElement element = find(selector, 30);
<ide> if (element != null) {
<ide> element.click();
<del> getLogger().debug(MARKER_PASS, "clicked optional '" + selector.elementName() + "'");
<add> getLogger().info(MARKER_PASS, "clicked optional '" + selector.elementName() + "'");
<ide> }
<ide> else {
<ide> getLogger().debug("did not click optional '" + selector.elementName() + "'");
|
|
JavaScript
|
mit
|
e94c3f2eb896084052d60a86760e722174bd9819
| 0 |
keithiopia/spotlight,keithiopia/spotlight,tijmenb/spotlight,tijmenb/spotlight,keithiopia/spotlight,alphagov/spotlight,alphagov/spotlight,alphagov/spotlight,tijmenb/spotlight
|
define([
'extensions/collections/matrix'
],
function (MatrixCollection) {
var MultiStatsCollection = MatrixCollection.extend({
initialize: function (attrs, options) {
options = options || {};
this.stats = options.stats;
this.period = options.period;
MatrixCollection.prototype.initialize.apply(this, arguments);
},
getAttrNames: function () {
return _.map(this.stats, function (stat) {
return stat.attr;
});
},
queryParams: function () {
return {
period: this.period,
collect: this.getAttrNames()
};
},
parse: function (response) {
var latestIndexWithValues = -1;
var data = _.map(response.data, function (item, index) {
var res = {
_start_at: item._start_at,
_end_at: item._end_at
};
_.each(this.getAttrNames(), function (attr) {
if (item[attr] && item[attr].length) {
latestIndexWithValues = index;
res[attr] = item[attr][0];
}
}, this);
return res;
}, this);
data = data.slice(0, latestIndexWithValues + 1);
return {
id: 'multistats',
title: 'MultiStats',
values: data
};
}
});
return MultiStatsCollection;
});
|
app/common/collections/multi_stats.js
|
define([
'extensions/collections/matrix'
],
function (MatrixCollection) {
var MultiStatsCollection = MatrixCollection.extend({
initialize: function (attrs, options) {
options = options || {};
this.stats = options.stats;
this.period = options.period;
MatrixCollection.prototype.initialize.apply(this, arguments);
},
getAttrNames: function () {
return _.map(this.stats, function (stat) {
return stat.attr;
});
},
queryParams: function () {
return {
period: this.period,
collect: this.getAttrNames()
};
},
parse: function (response) {
var latestIndexWithValues = -1;
var data = _.map(response.data, function (item, index) {
var res = {
_start_at: item._start_at,
_end_at: item._end_at
};
_.each(this.getAttrNames(), function (attr) {
if (item[attr] && item[attr].length) {
latestIndexWithValues = index;
res[attr] = item[attr][0];
}
}, this);
return res;
}, this);
data = data.slice(0, latestIndexWithValues + 1);
return {
id: 'multistats',
title: 'MultiStats',
values: data
};
}
});
return MultiStatsCollection;
});
|
Indentation fix
|
app/common/collections/multi_stats.js
|
Indentation fix
|
<ide><path>pp/common/collections/multi_stats.js
<ide>
<ide> getAttrNames: function () {
<ide> return _.map(this.stats, function (stat) {
<del> return stat.attr;
<add> return stat.attr;
<ide> });
<ide> },
<ide>
|
|
JavaScript
|
mit
|
8b15b74d0180fa386b42b5b6404a1260a59e9417
| 0 |
rosmod/webgme-rosmod,rosmod/webgme-rosmod
|
/*globals define, WebGMEGlobal*/
/*jshint browser: true*/
/**
* Generated by VisualizerGenerator 0.1.0 from webgme on Sat Apr 16 2016 08:51:41 GMT-0700 (PDT).
*/
define(['js/Constants',
'rosmod/meta',
'js/Utils/GMEConcepts',
'js/NodePropertyNames'
], function (CONSTANTS,
MetaTypes,
GMEConcepts,
nodePropertyNames) {
'use strict';
var CodeEditorControl;
// the final leaf is a 'mode' object for the CodeMirror to use
var TypeToAttributeMap = {
'Project': {
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
},
'Package': {
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
},
'Message': {
'Definition': {
name:'text/x-c++src',
keywords: {
'int8': 'int8',
'int16': 'int16',
'int32': 'int32',
'int64': 'int64',
'uint8': 'uint8',
'uint16': 'uint16',
'uint32': 'uint32',
'uint64': 'uint64',
'bool': 'bool',
'string': 'string',
'float32': 'float32',
'float64': 'float64',
'time': 'time',
'duration': 'duration'
},
useCPP:true
}
},
'Service': {
'Definition': {
name:'text/x-c++src',
keywords: {
'int8': 'int8',
'int16': 'int16',
'int32': 'int32',
'int64': 'int64',
'uint8': 'uint8',
'uint16': 'uint16',
'uint32': 'uint32',
'uint64': 'uint64',
'bool': 'bool',
'string': 'string',
'float32': 'float32',
'float64': 'float64',
'time': 'time',
'duration': 'duration'
},
useCPP:true
}
},
'Component': {
'Forwards': {name:'text/x-c++src', useCPP:true},
'Members': {name:'text/x-c++src', useCPP:true},
'Definitions': {name:'text/x-c++src', useCPP:true},
'Initialization': {name:'text/x-c++src', useCPP:true},
'Destruction': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
},
'Timer': {
'Operation': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
'AbstractBusinessLogic': {name:'text/x-c++src', useCPP:true},
},
'Server': {
'Operation': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
'AbstractBusinessLogic': {name:'text/x-c++src', useCPP:true},
},
'Subscriber': {
'Operation': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
'AbstractBusinessLogic': {name:'text/x-c++src', useCPP:true},
},
};
CodeEditorControl = function (options) {
this._logger = options.logger.fork('Control');
this.metaTypes = MetaTypes;
this._client = options.client;
// Initialize core collections and variables
this._widget = options.widget;
this.currentNodeInfo = {id: null, children: [], parentId: null};
this._topNode = '/v';
this._initWidgetEventHandlers();
this._logger.debug('ctor finished');
};
CodeEditorControl.prototype._initWidgetEventHandlers = function () {
this._widget.onNodeClick = function (id) {
// Change the current active object
WebGMEGlobal.State.registerActiveObject(id);
};
};
/* * * * * * * * Visualizer content update callbacks * * * * * * * */
// One major concept here is with managing the territory. The territory
// defines the parts of the project that the visualizer is interested in
// (this allows the browser to then only load those relevant parts).
CodeEditorControl.prototype.selectedObjectChanged = function (nodeId) {
var self = this,
desc,
nodeName;
self._logger.debug('activeObject nodeId \'' + nodeId + '\'');
// Remove current territory patterns
if (self._territoryId) {
self._client.removeUI(self._territoryId);
}
this.currentNodeInfo.id = nodeId;
this.currentNodeInfo.parentId = undefined;
if (nodeId) {
desc = this._getObjectDescriptor(nodeId);
nodeName = (desc && desc.name);
if (desc) {
this.currentNodeInfo.parentId = desc.parentId;
}
this._refreshBtnModelHierarchyUp();
// Put new node's info into territory rules
self._selfPatterns = {};
self._selfPatterns[nodeId] = {children: 0}; // Territory "rule"
self._territoryId = self._client.addUI(self, function (events) {
self._eventCallback(events);
});
// Update the territory
self._client.updateTerritory(self._territoryId, self._selfPatterns);
}
};
CodeEditorControl.prototype._refreshBtnModelHierarchyUp = function () {
if (this.currentNodeInfo.id && this.currentNodeInfo.id !== this._topNode) {
this.$btnModelHierarchyUp.show();
} else {
this.$btnModelHierarchyUp.hide();
}
};
// This next function retrieves the relevant node information for the widget
CodeEditorControl.prototype._getObjectDescriptor = function (nodeId) {
var self = this;
var client = this._client;
var nodeObj = client.getNode(nodeId),
objDescriptor;
if (nodeObj) {
objDescriptor = {
'id': undefined,
'name': undefined,
'childrenIds': undefined,
'parentId': undefined,
'isConnection': false,
'codeAttributes': {}
};
var baseId = nodeObj.getBaseId();
var metaNames = Object.keys(self.metaTypes);
var nodeMetaName = metaNames.filter(function(n) {
return self.metaTypes[n] == baseId;
})[0];
if (nodeMetaName && TypeToAttributeMap[nodeMetaName]) {
var attrNames = Object.keys(TypeToAttributeMap[nodeMetaName]);
attrNames.map(function(attrName) {
var value = nodeObj.getAttribute(attrName);
if (!value) value = '';
objDescriptor.codeAttributes[attrName] = {
value: value,
mode: TypeToAttributeMap[nodeMetaName][attrName]
};
});
}
objDescriptor.id = nodeObj.getId();
objDescriptor.name = nodeObj.getAttribute('name');
objDescriptor.childrenIds = nodeObj.getChildrenIds();
objDescriptor.childrenNum = objDescriptor.childrenIds.length;
objDescriptor.parentId = nodeObj.getParentId();
objDescriptor.isConnection = GMEConcepts.isConnection(nodeId); // GMEConcepts can be helpful
}
return objDescriptor;
};
/* * * * * * * * Node Event Handling * * * * * * * */
CodeEditorControl.prototype._eventCallback = function (events) {
var i = events ? events.length : 0,
event;
this._logger.debug('_eventCallback \'' + i + '\' items');
while (i--) {
event = events[i];
switch (event.etype) {
case CONSTANTS.TERRITORY_EVENT_LOAD:
this._onLoad(event.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UPDATE:
this._onUpdate(event.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UNLOAD:
this._onUnload(event.eid);
break;
default:
break;
}
}
this._logger.debug('_eventCallback \'' + events.length + '\' items - DONE');
};
CodeEditorControl.prototype._onLoad = function (gmeId) {
var description = this._getObjectDescriptor(gmeId);
this._widget.addNode(description);
};
CodeEditorControl.prototype._onUpdate = function (gmeId) {
var description = this._getObjectDescriptor(gmeId);
this._widget.updateNode(description);
};
CodeEditorControl.prototype._onUnload = function (gmeId) {
this._widget.removeNode(gmeId);
};
CodeEditorControl.prototype._stateActiveObjectChanged = function (model, activeObjectId) {
this.selectedObjectChanged(activeObjectId);
};
/* * * * * * * * Visualizer life cycle callbacks * * * * * * * */
CodeEditorControl.prototype.destroy = function () {
this._detachClientEventListeners();
this._removeToolbarItems();
};
CodeEditorControl.prototype._attachClientEventListeners = function () {
this._detachClientEventListeners();
WebGMEGlobal.State.on('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged, this);
};
CodeEditorControl.prototype._detachClientEventListeners = function () {
WebGMEGlobal.State.off('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged);
};
CodeEditorControl.prototype.onActivate = function () {
this._attachClientEventListeners();
this._displayToolbarItems();
if (this.currentNodeInfo && typeof this.currentNodeInfo.id === 'string') {
WebGMEGlobal.State.registerSuppressVisualizerFromNode(true);
WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.id);
WebGMEGlobal.State.registerSuppressVisualizerFromNode(false);
}
};
CodeEditorControl.prototype.onDeactivate = function () {
this._detachClientEventListeners();
this._hideToolbarItems();
};
/* * * * * * * * * * Updating the toolbar * * * * * * * * * */
CodeEditorControl.prototype._displayToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = this._toolbarItems.length; i--;) {
this._toolbarItems[i].show();
}
} else {
this._initializeToolbar();
}
};
CodeEditorControl.prototype._hideToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = this._toolbarItems.length; i--;) {
this._toolbarItems[i].hide();
}
}
};
CodeEditorControl.prototype._removeToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = this._toolbarItems.length; i--;) {
this._toolbarItems[i].destroy();
}
}
};
CodeEditorControl.prototype._onModelHierarchyUp = function () {
var myId = this.currentNodeInfo.id;
if (this.currentNodeInfo.parentId ||
this.currentNodeInfo.parentId === CONSTANTS.PROJECT_ROOT_ID) {
WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.parentId);
WebGMEGlobal.State.registerActiveSelection([myId]);
}
};
CodeEditorControl.prototype._initializeToolbar = function () {
var self = this,
toolBar = WebGMEGlobal.Toolbar;
this._toolbarItems = [];
this._toolbarItems.push(toolBar.addSeparator());
/************** GOTO PARENT IN HIERARCHY BUTTON ****************/
this.$btnModelHierarchyUp = toolBar.addButton({
title: 'Go to parent',
icon: 'glyphicon glyphicon-circle-arrow-up',
clickFn: function (/*data*/) {
self._onModelHierarchyUp();
}
});
this._toolbarItems.push(this.$btnModelHierarchyUp);
this.$btnModelHierarchyUp.hide();
this._toolbarInitialized = true;
};
return CodeEditorControl;
});
|
src/visualizers/panels/CodeEditor/CodeEditorControl.js
|
/*globals define, WebGMEGlobal*/
/*jshint browser: true*/
/**
* Generated by VisualizerGenerator 0.1.0 from webgme on Sat Apr 16 2016 08:51:41 GMT-0700 (PDT).
*/
define(['js/Constants',
'rosmod/meta',
'js/Utils/GMEConcepts',
'js/NodePropertyNames'
], function (CONSTANTS,
MetaTypes,
GMEConcepts,
nodePropertyNames) {
'use strict';
var CodeEditorControl;
// the final leaf is a 'mode' object for the CodeMirror to use
var TypeToAttributeMap = {
'Project': {
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
},
'Package': {
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
},
'Message': {
'Definition': {
name:'text/x-c++src',
keywords: {
'int8': 'int8',
'int16': 'int16',
'int32': 'int32',
'int64': 'int64',
'uint8': 'uint8',
'uint16': 'uint16',
'uint32': 'uint32',
'uint64': 'uint64',
'bool': 'bool',
'string': 'string',
'float32': 'float32',
'float64': 'float64',
'time': 'time',
'duration': 'duration'
},
useCPP:true
}
},
'Service': {
'Definition': {
name:'text/x-c++src',
keywords: {
'int8': 'int8',
'int16': 'int16',
'int32': 'int32',
'int64': 'int64',
'uint8': 'uint8',
'uint16': 'uint16',
'uint32': 'uint32',
'uint64': 'uint64',
'bool': 'bool',
'string': 'string',
'float32': 'float32',
'float64': 'float64',
'time': 'time',
'duration': 'duration'
},
useCPP:true
}
},
'Component': {
'Forwards': {name:'text/x-c++src', useCPP:true},
'Members': {name:'text/x-c++src', useCPP:true},
'Definitions': {name:'text/x-c++src', useCPP:true},
'Initialization': {name:'text/x-c++src', useCPP:true},
'Destruction': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
},
'Timer': {
'Operation': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
'AbstractBusinessLogic': {name:'text/x-c++src', useCPP:true},
},
'Server': {
'Operation': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
'AbstractBusinessLogic': {name:'text/x-c++src', useCPP:true},
},
'Subscriber': {
'Operation': {name:'text/x-c++src', useCPP:true},
'Authors': {name:'markdown'},
'Brief Description': {name:'markdown'},
'Detailed Description': {name:'markdown'},
'AbstractBusinessLogic': {name:'text/x-c++src', useCPP:true},
},
};
CodeEditorControl = function (options) {
this._logger = options.logger.fork('Control');
this.metaTypes = MetaTypes;
this._client = options.client;
// Initialize core collections and variables
this._widget = options.widget;
this._currentNodeId = null;
this._currentNodeParentId = undefined;
this._initWidgetEventHandlers();
this._logger.debug('ctor finished');
};
CodeEditorControl.prototype._initWidgetEventHandlers = function () {
this._widget.onNodeClick = function (id) {
// Change the current active object
WebGMEGlobal.State.registerActiveObject(id);
};
};
/* * * * * * * * Visualizer content update callbacks * * * * * * * */
// One major concept here is with managing the territory. The territory
// defines the parts of the project that the visualizer is interested in
// (this allows the browser to then only load those relevant parts).
CodeEditorControl.prototype.selectedObjectChanged = function (nodeId) {
var desc = this._getObjectDescriptor(nodeId),
self = this;
self._logger.debug('activeObject nodeId \'' + nodeId + '\'');
// Remove current territory patterns
if (self._currentNodeId) {
self._client.removeUI(self._territoryId);
}
self._currentNodeId = nodeId;
self._currentNodeParentId = undefined;
if (self._currentNodeId) {
// Put new node's info into territory rules
self._selfPatterns = {};
self._selfPatterns[nodeId] = {children: 0}; // Territory "rule"
if (desc.parentId) {
self.$btnModelHierarchyUp.show();
} else {
self.$btnModelHierarchyUp.hide();
}
self._currentNodeParentId = desc.parentId;
self._territoryId = self._client.addUI(self, function (events) {
self._eventCallback(events);
});
// Update the territory
self._client.updateTerritory(self._territoryId, self._selfPatterns);
}
};
// This next function retrieves the relevant node information for the widget
CodeEditorControl.prototype._getObjectDescriptor = function (nodeId) {
var self = this;
var client = this._client;
var nodeObj = client.getNode(nodeId),
objDescriptor;
if (nodeObj) {
objDescriptor = {
'id': undefined,
'name': undefined,
'childrenIds': undefined,
'parentId': undefined,
'isConnection': false,
'codeAttributes': {}
};
var baseId = nodeObj.getBaseId();
var metaNames = Object.keys(self.metaTypes);
var nodeMetaName = metaNames.filter(function(n) {
return self.metaTypes[n] == baseId;
})[0];
if (nodeMetaName && TypeToAttributeMap[nodeMetaName]) {
var attrNames = Object.keys(TypeToAttributeMap[nodeMetaName]);
attrNames.map(function(attrName) {
var value = nodeObj.getAttribute(attrName);
if (!value) value = '';
objDescriptor.codeAttributes[attrName] = {
value: value,
mode: TypeToAttributeMap[nodeMetaName][attrName]
};
});
}
objDescriptor.id = nodeObj.getId();
objDescriptor.name = nodeObj.getAttribute('name');
objDescriptor.childrenIds = nodeObj.getChildrenIds();
objDescriptor.childrenNum = objDescriptor.childrenIds.length;
objDescriptor.parentId = nodeObj.getParentId();
objDescriptor.isConnection = GMEConcepts.isConnection(nodeId); // GMEConcepts can be helpful
}
return objDescriptor;
};
/* * * * * * * * Node Event Handling * * * * * * * */
CodeEditorControl.prototype._eventCallback = function (events) {
var i = events ? events.length : 0,
event;
this._logger.debug('_eventCallback \'' + i + '\' items');
while (i--) {
event = events[i];
switch (event.etype) {
case CONSTANTS.TERRITORY_EVENT_LOAD:
this._onLoad(event.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UPDATE:
this._onUpdate(event.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UNLOAD:
this._onUnload(event.eid);
break;
default:
break;
}
}
this._logger.debug('_eventCallback \'' + events.length + '\' items - DONE');
};
CodeEditorControl.prototype._onLoad = function (gmeId) {
var description = this._getObjectDescriptor(gmeId);
this._widget.addNode(description);
};
CodeEditorControl.prototype._onUpdate = function (gmeId) {
var description = this._getObjectDescriptor(gmeId);
this._widget.updateNode(description);
};
CodeEditorControl.prototype._onUnload = function (gmeId) {
this._widget.removeNode(gmeId);
};
CodeEditorControl.prototype._stateActiveObjectChanged = function (model, activeObjectId) {
this.selectedObjectChanged(activeObjectId);
};
/* * * * * * * * Visualizer life cycle callbacks * * * * * * * */
CodeEditorControl.prototype.destroy = function () {
this._detachClientEventListeners();
this._removeToolbarItems();
};
CodeEditorControl.prototype._attachClientEventListeners = function () {
this._detachClientEventListeners();
WebGMEGlobal.State.on('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged, this);
};
CodeEditorControl.prototype._detachClientEventListeners = function () {
WebGMEGlobal.State.off('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged);
};
CodeEditorControl.prototype.onActivate = function () {
this._attachClientEventListeners();
this._displayToolbarItems();
};
CodeEditorControl.prototype.onDeactivate = function () {
this._detachClientEventListeners();
this._hideToolbarItems();
};
/* * * * * * * * * * Updating the toolbar * * * * * * * * * */
CodeEditorControl.prototype._displayToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = this._toolbarItems.length; i--;) {
this._toolbarItems[i].show();
}
} else {
this._initializeToolbar();
}
};
CodeEditorControl.prototype._hideToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = this._toolbarItems.length; i--;) {
this._toolbarItems[i].hide();
}
}
};
CodeEditorControl.prototype._removeToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = this._toolbarItems.length; i--;) {
this._toolbarItems[i].destroy();
}
}
};
CodeEditorControl.prototype._initializeToolbar = function () {
var self = this,
toolBar = WebGMEGlobal.Toolbar;
this._toolbarItems = [];
this._toolbarItems.push(toolBar.addSeparator());
/************** Go to hierarchical parent button ****************/
this.$btnModelHierarchyUp = toolBar.addButton({
title: 'Go to parent',
icon: 'glyphicon glyphicon-circle-arrow-up',
clickFn: function () { // (data)
WebGMEGlobal.State.registerActiveObject(self._currentNodeParentId);
}
});
this._toolbarItems.push(this.$btnModelHierarchyUp);
this.$btnModelHierarchyUp.hide();
this._toolbarInitialized = true;
};
return CodeEditorControl;
});
|
updated to fix heirarchy-up button in codeEditor viz. closes #74
|
src/visualizers/panels/CodeEditor/CodeEditorControl.js
|
updated to fix heirarchy-up button in codeEditor viz. closes #74
|
<ide><path>rc/visualizers/panels/CodeEditor/CodeEditorControl.js
<ide> // Initialize core collections and variables
<ide> this._widget = options.widget;
<ide>
<del> this._currentNodeId = null;
<del> this._currentNodeParentId = undefined;
<add> this.currentNodeInfo = {id: null, children: [], parentId: null};
<add> this._topNode = '/v';
<ide>
<ide> this._initWidgetEventHandlers();
<ide>
<ide> // defines the parts of the project that the visualizer is interested in
<ide> // (this allows the browser to then only load those relevant parts).
<ide> CodeEditorControl.prototype.selectedObjectChanged = function (nodeId) {
<del> var desc = this._getObjectDescriptor(nodeId),
<del> self = this;
<add> var self = this,
<add> desc,
<add> nodeName;
<ide>
<ide> self._logger.debug('activeObject nodeId \'' + nodeId + '\'');
<ide>
<ide> // Remove current territory patterns
<del> if (self._currentNodeId) {
<add> if (self._territoryId) {
<ide> self._client.removeUI(self._territoryId);
<ide> }
<ide>
<del> self._currentNodeId = nodeId;
<del> self._currentNodeParentId = undefined;
<del>
<del> if (self._currentNodeId) {
<add> this.currentNodeInfo.id = nodeId;
<add> this.currentNodeInfo.parentId = undefined;
<add>
<add> if (nodeId) {
<add> desc = this._getObjectDescriptor(nodeId);
<add> nodeName = (desc && desc.name);
<add> if (desc) {
<add> this.currentNodeInfo.parentId = desc.parentId;
<add> }
<add>
<add> this._refreshBtnModelHierarchyUp();
<add>
<ide> // Put new node's info into territory rules
<ide> self._selfPatterns = {};
<ide> self._selfPatterns[nodeId] = {children: 0}; // Territory "rule"
<ide>
<del> if (desc.parentId) {
<del> self.$btnModelHierarchyUp.show();
<del> } else {
<del> self.$btnModelHierarchyUp.hide();
<del> }
<del>
<del> self._currentNodeParentId = desc.parentId;
<del>
<ide> self._territoryId = self._client.addUI(self, function (events) {
<ide> self._eventCallback(events);
<ide> });
<ide>
<ide> // Update the territory
<ide> self._client.updateTerritory(self._territoryId, self._selfPatterns);
<add> }
<add> };
<add>
<add> CodeEditorControl.prototype._refreshBtnModelHierarchyUp = function () {
<add> if (this.currentNodeInfo.id && this.currentNodeInfo.id !== this._topNode) {
<add> this.$btnModelHierarchyUp.show();
<add> } else {
<add> this.$btnModelHierarchyUp.hide();
<ide> }
<ide> };
<ide>
<ide> CodeEditorControl.prototype.onActivate = function () {
<ide> this._attachClientEventListeners();
<ide> this._displayToolbarItems();
<add>
<add> if (this.currentNodeInfo && typeof this.currentNodeInfo.id === 'string') {
<add> WebGMEGlobal.State.registerSuppressVisualizerFromNode(true);
<add> WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.id);
<add> WebGMEGlobal.State.registerSuppressVisualizerFromNode(false);
<add> }
<ide> };
<ide>
<ide> CodeEditorControl.prototype.onDeactivate = function () {
<ide> }
<ide> };
<ide>
<add> CodeEditorControl.prototype._onModelHierarchyUp = function () {
<add> var myId = this.currentNodeInfo.id;
<add> if (this.currentNodeInfo.parentId ||
<add> this.currentNodeInfo.parentId === CONSTANTS.PROJECT_ROOT_ID) {
<add> WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.parentId);
<add> WebGMEGlobal.State.registerActiveSelection([myId]);
<add> }
<add> };
<add>
<ide> CodeEditorControl.prototype._initializeToolbar = function () {
<ide> var self = this,
<ide> toolBar = WebGMEGlobal.Toolbar;
<ide>
<ide> this._toolbarItems.push(toolBar.addSeparator());
<ide>
<del> /************** Go to hierarchical parent button ****************/
<del>
<add> /************** GOTO PARENT IN HIERARCHY BUTTON ****************/
<ide> this.$btnModelHierarchyUp = toolBar.addButton({
<ide> title: 'Go to parent',
<ide> icon: 'glyphicon glyphicon-circle-arrow-up',
<del> clickFn: function () { // (data)
<del> WebGMEGlobal.State.registerActiveObject(self._currentNodeParentId);
<add> clickFn: function (/*data*/) {
<add> self._onModelHierarchyUp();
<ide> }
<ide> });
<ide> this._toolbarItems.push(this.$btnModelHierarchyUp);
<add>
<ide> this.$btnModelHierarchyUp.hide();
<ide>
<ide> this._toolbarInitialized = true;
|
|
Java
|
apache-2.0
|
f2e12ea62206368e627ebdbf1ff3f73fd6ec82a4
| 0 |
JetBrains/xodus,JetBrains/xodus,JetBrains/xodus
|
/**
* Copyright 2010 - 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.io;
import jetbrains.exodus.ExodusException;
import jetbrains.exodus.core.dataStructures.ObjectCache;
import jetbrains.exodus.util.SharedRandomAccessFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static jetbrains.exodus.core.dataStructures.ObjectCacheBase.CriticalSection;
final class SharedOpenFilesCache {
private static final Object syncObject = new Object();
private static int cacheSize = 0;
private static volatile SharedOpenFilesCache theCache = null;
private final ObjectCache<File, SharedRandomAccessFile> cache;
private SharedOpenFilesCache(final int openFiles) {
cache = new ObjectCache<>(openFiles);
}
static void setSize(final int cacheSize) {
if (cacheSize <= 0) {
throw new IllegalArgumentException("Cache size must be a positive integer value");
}
SharedOpenFilesCache.cacheSize = cacheSize;
}
static SharedOpenFilesCache getInstance() {
if (cacheSize == 0) {
throw new ExodusException("Size of SharedOpenFilesCache is not set");
}
SharedOpenFilesCache result = theCache;
if (result == null) {
synchronized (syncObject) {
result = theCache;
if (result == null) {
result = theCache = new SharedOpenFilesCache(cacheSize);
}
}
}
return result;
}
/**
* For tests only!!!
*/
static void invalidate() throws IOException {
final SharedOpenFilesCache obsolete;
synchronized (syncObject) {
obsolete = theCache;
theCache = null;
}
if (obsolete != null) {
obsolete.clear();
}
}
@NotNull
SharedRandomAccessFile getCachedFile(@NotNull final File file, @NotNull final String mode) throws IOException {
SharedRandomAccessFile result;
try (CriticalSection ignored = cache.newCriticalSection()) {
result = cache.tryKey(file);
if (result != null && result.employ() > 1) {
result.close();
result = null;
}
}
if (result == null) {
result = new SharedRandomAccessFile(file, mode);
SharedRandomAccessFile obsolete = null;
try (CriticalSection ignored = cache.newCriticalSection()) {
if (cache.getObject(file) == null) {
result.employ();
obsolete = cache.cacheObject(file, result);
}
}
if (obsolete != null) {
obsolete.close();
}
}
return result;
}
@Nullable
SharedRandomAccessFile removeFile(@NotNull final File file) throws IOException {
final SharedRandomAccessFile result;
try (CriticalSection ignored = cache.newCriticalSection()) {
result = cache.remove(file);
}
if (result != null) {
result.close();
}
return result;
}
List<SharedRandomAccessFile> removeDirectory(@NotNull final File dir) throws IOException {
final List<SharedRandomAccessFile> result = new ArrayList<>();
final List<File> obsoleteFiles = new ArrayList<>();
try (CriticalSection ignored = cache.newCriticalSection()) {
final Iterator<File> keys = cache.keys();
while (keys.hasNext()) {
final File file = keys.next();
if (file.getParentFile().equals(dir)) {
obsoleteFiles.add(file);
result.add(cache.getObject(file));
}
}
for (final File file : obsoleteFiles) {
cache.remove(file);
}
}
for (final SharedRandomAccessFile obsolete : result) {
obsolete.close();
}
return result;
}
private void clear() throws IOException {
final List<SharedRandomAccessFile> openFiles = new ArrayList<>();
try (CriticalSection ignored = cache.newCriticalSection()) {
final Iterator<SharedRandomAccessFile> it = cache.values();
while (it.hasNext()) {
openFiles.add(it.next());
}
cache.clear();
}
for (final SharedRandomAccessFile file : openFiles) {
file.close();
}
}
}
|
environment/src/main/java/jetbrains/exodus/io/SharedOpenFilesCache.java
|
/**
* Copyright 2010 - 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.io;
import jetbrains.exodus.ExodusException;
import jetbrains.exodus.core.dataStructures.ObjectCache;
import jetbrains.exodus.util.SharedRandomAccessFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static jetbrains.exodus.core.dataStructures.ObjectCacheBase.CriticalSection;
final class SharedOpenFilesCache {
private static final Object syncObject = new Object();
private static int cacheSize = 0;
private static SharedOpenFilesCache theCache = null;
private final ObjectCache<File, SharedRandomAccessFile> cache;
private SharedOpenFilesCache(final int openFiles) {
cache = new ObjectCache<>(openFiles);
}
static void setSize(final int cacheSize) {
if (cacheSize <= 0) {
throw new IllegalArgumentException("Cache size must be a positive integer value");
}
SharedOpenFilesCache.cacheSize = cacheSize;
}
static SharedOpenFilesCache getInstance() {
if (cacheSize == 0) {
throw new ExodusException("Size of SharedOpenFilesCache is not set");
}
SharedOpenFilesCache result = theCache;
if (result == null) {
synchronized (syncObject) {
result = theCache;
if (result == null) {
result = theCache = new SharedOpenFilesCache(cacheSize);
}
}
}
return result;
}
/**
* For tests only!!!
*/
static void invalidate() throws IOException {
final SharedOpenFilesCache obsolete;
synchronized (syncObject) {
obsolete = theCache;
theCache = null;
}
if (obsolete != null) {
obsolete.clear();
}
}
@NotNull
SharedRandomAccessFile getCachedFile(@NotNull final File file, @NotNull final String mode) throws IOException {
SharedRandomAccessFile result;
try (CriticalSection ignored = cache.newCriticalSection()) {
result = cache.tryKey(file);
if (result != null && result.employ() > 1) {
result.close();
result = null;
}
}
if (result == null) {
result = new SharedRandomAccessFile(file, mode);
SharedRandomAccessFile obsolete = null;
try (CriticalSection ignored = cache.newCriticalSection()) {
if (cache.getObject(file) == null) {
result.employ();
obsolete = cache.cacheObject(file, result);
}
}
if (obsolete != null) {
obsolete.close();
}
}
return result;
}
@Nullable
SharedRandomAccessFile removeFile(@NotNull final File file) throws IOException {
final SharedRandomAccessFile result;
try (CriticalSection ignored = cache.newCriticalSection()) {
result = cache.remove(file);
}
if (result != null) {
result.close();
}
return result;
}
List<SharedRandomAccessFile> removeDirectory(@NotNull final File dir) throws IOException {
final List<SharedRandomAccessFile> result = new ArrayList<>();
final List<File> obsoleteFiles = new ArrayList<>();
try (CriticalSection ignored = cache.newCriticalSection()) {
final Iterator<File> keys = cache.keys();
while (keys.hasNext()) {
final File file = keys.next();
if (file.getParentFile().equals(dir)) {
obsoleteFiles.add(file);
result.add(cache.getObject(file));
}
}
for (final File file : obsoleteFiles) {
cache.remove(file);
}
}
for (final SharedRandomAccessFile obsolete : result) {
obsolete.close();
}
return result;
}
private void clear() throws IOException {
final List<SharedRandomAccessFile> openFiles = new ArrayList<>();
try (CriticalSection ignored = cache.newCriticalSection()) {
final Iterator<SharedRandomAccessFile> it = cache.values();
while (it.hasNext()) {
openFiles.add(it.next());
}
cache.clear();
}
for (final SharedRandomAccessFile file : openFiles) {
file.close();
}
}
}
|
XODUS-CR-34: volatile ref for singleton
|
environment/src/main/java/jetbrains/exodus/io/SharedOpenFilesCache.java
|
XODUS-CR-34: volatile ref for singleton
|
<ide><path>nvironment/src/main/java/jetbrains/exodus/io/SharedOpenFilesCache.java
<ide>
<ide> private static final Object syncObject = new Object();
<ide> private static int cacheSize = 0;
<del> private static SharedOpenFilesCache theCache = null;
<add> private static volatile SharedOpenFilesCache theCache = null;
<ide>
<ide> private final ObjectCache<File, SharedRandomAccessFile> cache;
<ide>
|
|
Java
|
bsd-2-clause
|
3205187975350e4b8c25d6522c42eaa490498c82
| 0 |
mosoft521/jodd,mohanaraosv/jodd,southwolf/jodd,mohanaraosv/jodd,javachengwc/jodd,tempbottle/jodd,tempbottle/jodd,oblac/jodd,Artemish/jodd,mohanaraosv/jodd,wjw465150/jodd,wjw465150/jodd,wsldl123292/jodd,wjw465150/jodd,mosoft521/jodd,vilmospapp/jodd,mohanaraosv/jodd,oblac/jodd,mtakaki/jodd,wjw465150/jodd,wsldl123292/jodd,southwolf/jodd,mtakaki/jodd,oetting/jodd,oetting/jodd,Artemish/jodd,oblac/jodd,Artemish/jodd,javachengwc/jodd,oetting/jodd,javachengwc/jodd,Artemish/jodd,oblac/jodd,mosoft521/jodd,mtakaki/jodd,wsldl123292/jodd,vilmospapp/jodd,southwolf/jodd,vilmospapp/jodd,wsldl123292/jodd,mtakaki/jodd,javachengwc/jodd,tempbottle/jodd,tempbottle/jodd,southwolf/jodd,vilmospapp/jodd,oetting/jodd,mosoft521/jodd,vilmospapp/jodd,Artemish/jodd
|
// Copyright (c) 2003-2013, Jodd Team (jodd.org). All Rights Reserved.
package jodd.lagarto.dom;
import jodd.csselly.CSSelly;
import jodd.csselly.Combinator;
import jodd.csselly.CssSelector;
import jodd.util.StringUtil;
import java.util.LinkedList;
import java.util.List;
/**
* Node selector selects DOM nodes using {@link CSSelly CSS3 selectors}.
* Group of queries are supported.
*/
public class NodeSelector {
protected final Node rootNode;
public NodeSelector(Node rootNode) {
this.rootNode = rootNode;
}
// ---------------------------------------------------------------- selector
/**
* Selects nodes using CSS3 selector query.
*/
public LinkedList<Node> select(String query) {
String[] singleQueries = StringUtil.splitc(query, ',');
LinkedList<Node> results = new LinkedList<Node>();
for (String singleQuery : singleQueries) {
CSSelly csselly = createCSSelly(singleQuery);
List<CssSelector> selectors = csselly.parse();
for (Node selectedNode : select(rootNode, selectors)) {
if (!results.contains(selectedNode)) {
results.add(selectedNode);
}
}
}
return results;
}
public LinkedList<Node> select(List<List<CssSelector>> selectorsList) {
LinkedList<Node> results = new LinkedList<Node>();
for (List<CssSelector> selectors : selectorsList) {
for (Node selectedNode : select(rootNode, selectors)) {
if (!results.contains(selectedNode)) {
results.add(selectedNode);
}
}
}
return results;
}
/**
* Creates {@link CSSelly} instance for parsing files.
*/
protected CSSelly createCSSelly(String cssQuery) {
return new CSSelly(cssQuery);
}
/**
* Selects nodes using CSS3 selector query and returns the very first one.
*/
public Node selectFirst(String query) {
List<Node> selectedNodes = select(query);
if (selectedNodes.isEmpty()) {
return null;
}
return selectedNodes.get(0);
}
public LinkedList<Node> select(NodeFilter nodeFilter) {
LinkedList<Node> nodes = new LinkedList<Node>();
walk(rootNode, nodeFilter, nodes);
return nodes;
}
public Node selectFirst(NodeFilter nodeFilter) {
List<Node> selectedNodes = select(nodeFilter);
if (selectedNodes.isEmpty()) {
return null;
}
return selectedNodes.get(0);
}
// ---------------------------------------------------------------- internal
protected void walk(Node rootNode, NodeFilter nodeFilter, LinkedList<Node> result) {
int childCount = rootNode.getChildNodesCount();
for (int i = 0; i < childCount; i++) {
Node node = rootNode.getChild(i);
if (nodeFilter.accept(node)) {
result.add(node);
}
walk(node, nodeFilter, result);
}
}
protected LinkedList<Node> select(Node rootNode, List<CssSelector> selectors) {
// start with the root node
LinkedList<Node> nodes = new LinkedList<Node>();
nodes.add(rootNode);
// iterate all selectors
for (CssSelector cssSelector : selectors) {
// create new set of results for current css selector
LinkedList<Node> selectedNodes = new LinkedList<Node>();
for (Node node : nodes) {
walk(node, cssSelector, selectedNodes);
}
// post-processing: filter out the results
LinkedList<Node> resultNodes = new LinkedList<Node>();
int index = 0;
for (Node node : selectedNodes) {
boolean match = filter(selectedNodes, node, cssSelector, index);
if (match == true) {
resultNodes.add(node);
}
index++;
}
// continue with results
nodes = resultNodes;
}
return nodes;
}
/**
* Walks over the child notes, maintaining the tree order and not using recursion.
*/
protected void walkDescendantsIteratively(LinkedList<Node> nodes, CssSelector cssSelector, LinkedList<Node> result) {
while (!nodes.isEmpty()) {
Node node = nodes.removeFirst();
selectAndAdd(node, cssSelector, result);
// append children in walking order to be processed right after this node
int childCount = node.getChildNodesCount();
for (int i = childCount - 1; i >= 0; i--) {
nodes.addFirst(node.getChild(i));
}
}
}
/**
* Finds nodes in the tree that matches single selector.
*/
protected void walk(Node rootNode, CssSelector cssSelector, LinkedList<Node> result) {
// previous combinator determines the behavior
CssSelector previousCssSelector = cssSelector.getPrevCssSelector();
Combinator combinator = previousCssSelector != null ?
previousCssSelector.getCombinator() :
Combinator.DESCENDANT;
switch (combinator) {
case DESCENDANT:
LinkedList<Node> nodes = new LinkedList<Node>();
int childCount = rootNode.getChildNodesCount();
for (int i = 0; i < childCount; i++) {
nodes.add(rootNode.getChild(i));
// recursive
// selectAndAdd(node, cssSelector, result);
// walk(node, cssSelector, result);
}
walkDescendantsIteratively(nodes, cssSelector, result);
break;
case CHILD:
childCount = rootNode.getChildNodesCount();
for (int i = 0; i < childCount; i++) {
Node node = rootNode.getChild(i);
selectAndAdd(node, cssSelector, result);
}
break;
case ADJACENT_SIBLING:
Node node = rootNode.getNextSiblingElement();
if (node != null) {
selectAndAdd(node, cssSelector, result);
}
break;
case GENERAL_SIBLING:
node = rootNode;
while (true) {
node = node.getNextSiblingElement();
if (node == null) {
break;
}
selectAndAdd(node, cssSelector, result);
}
break;
} }
/**
* Selects single node for single selector and appends it to the results.
*/
protected void selectAndAdd(Node node, CssSelector cssSelector, LinkedList<Node> result) {
// ignore all nodes that are not elements
if (node.getNodeType() != Node.NodeType.ELEMENT) {
return;
}
boolean matched = cssSelector.accept(node);
if (matched) {
// check for duplicates
if (result.contains(node)) {
return;
}
// no duplicate found, add it to the results
result.add(node);
}
}
/**
* Filter nodes.
*/
protected boolean filter(LinkedList<Node> currentResults, Node node, CssSelector cssSelector, int index) {
return cssSelector.accept(currentResults, node, index);
}
}
|
jodd-lagarto/src/main/java/jodd/lagarto/dom/NodeSelector.java
|
// Copyright (c) 2003-2013, Jodd Team (jodd.org). All Rights Reserved.
package jodd.lagarto.dom;
import jodd.csselly.CSSelly;
import jodd.csselly.Combinator;
import jodd.csselly.CssSelector;
import jodd.util.StringUtil;
import java.util.LinkedList;
import java.util.List;
/**
* Node selector selects DOM nodes using {@link CSSelly CSS3 selectors}.
* Group of queries are supported.
*/
public class NodeSelector {
protected final Node rootNode;
public NodeSelector(Node rootNode) {
this.rootNode = rootNode;
}
// ---------------------------------------------------------------- selector
/**
* Selects nodes using CSS3 selector query.
*/
public LinkedList<Node> select(String query) {
String[] singleQueries = StringUtil.splitc(query, ',');
LinkedList<Node> results = new LinkedList<Node>();
for (String singleQuery : singleQueries) {
CSSelly csselly = createCSSelly(singleQuery);
List<CssSelector> selectors = csselly.parse();
List<Node> selectedNodes = select(rootNode, selectors);
for (Node selectedNode : selectedNodes) {
if (results.contains(selectedNode) == false) {
results.add(selectedNode);
}
}
}
return results;
}
/**
* Creates {@link CSSelly} instance for parsing files.
*/
protected CSSelly createCSSelly(String cssQuery) {
return new CSSelly(cssQuery);
}
/**
* Selects nodes using CSS3 selector query and returns the very first one.
*/
public Node selectFirst(String query) {
List<Node> selectedNodes = select(query);
if (selectedNodes.isEmpty()) {
return null;
}
return selectedNodes.get(0);
}
public LinkedList<Node> select(NodeFilter nodeFilter) {
LinkedList<Node> nodes = new LinkedList<Node>();
walk(rootNode, nodeFilter, nodes);
return nodes;
}
public Node selectFirst(NodeFilter nodeFilter) {
List<Node> selectedNodes = select(nodeFilter);
if (selectedNodes.isEmpty()) {
return null;
}
return selectedNodes.get(0);
}
// ---------------------------------------------------------------- internal
protected void walk(Node rootNode, NodeFilter nodeFilter, LinkedList<Node> result) {
int childCount = rootNode.getChildNodesCount();
for (int i = 0; i < childCount; i++) {
Node node = rootNode.getChild(i);
if (nodeFilter.accept(node)) {
result.add(node);
}
walk(node, nodeFilter, result);
}
}
protected LinkedList<Node> select(Node rootNode, List<CssSelector> selectors) {
// start with the root node
LinkedList<Node> nodes = new LinkedList<Node>();
nodes.add(rootNode);
// iterate all selectors
for (CssSelector cssSelector : selectors) {
// create new set of results for current css selector
LinkedList<Node> selectedNodes = new LinkedList<Node>();
for (Node node : nodes) {
walk(node, cssSelector, selectedNodes);
}
// post-processing: filter out the results
LinkedList<Node> resultNodes = new LinkedList<Node>();
int index = 0;
for (Node node : selectedNodes) {
boolean match = filter(selectedNodes, node, cssSelector, index);
if (match == true) {
resultNodes.add(node);
}
index++;
}
// continue with results
nodes = resultNodes;
}
return nodes;
}
/**
* Walks over the child notes, maintaining the tree order and not using recursion.
*/
protected void walkDescendantsIteratively(LinkedList<Node> nodes, CssSelector cssSelector, LinkedList<Node> result) {
while (!nodes.isEmpty()) {
Node node = nodes.removeFirst();
selectAndAdd(node, cssSelector, result);
// append children in walking order to be processed right after this node
int childCount = node.getChildNodesCount();
for (int i = childCount - 1; i >= 0; i--) {
nodes.addFirst(node.getChild(i));
}
}
}
/**
* Finds nodes in the tree that matches single selector.
*/
protected void walk(Node rootNode, CssSelector cssSelector, LinkedList<Node> result) {
// previous combinator determines the behavior
CssSelector previousCssSelector = cssSelector.getPrevCssSelector();
Combinator combinator = previousCssSelector != null ?
previousCssSelector.getCombinator() :
Combinator.DESCENDANT;
switch (combinator) {
case DESCENDANT:
LinkedList<Node> nodes = new LinkedList<Node>();
int childCount = rootNode.getChildNodesCount();
for (int i = 0; i < childCount; i++) {
nodes.add(rootNode.getChild(i));
// recursive
// selectAndAdd(node, cssSelector, result);
// walk(node, cssSelector, result);
}
walkDescendantsIteratively(nodes, cssSelector, result);
break;
case CHILD:
childCount = rootNode.getChildNodesCount();
for (int i = 0; i < childCount; i++) {
Node node = rootNode.getChild(i);
selectAndAdd(node, cssSelector, result);
}
break;
case ADJACENT_SIBLING:
Node node = rootNode.getNextSiblingElement();
if (node != null) {
selectAndAdd(node, cssSelector, result);
}
break;
case GENERAL_SIBLING:
node = rootNode;
while (true) {
node = node.getNextSiblingElement();
if (node == null) {
break;
}
selectAndAdd(node, cssSelector, result);
}
break;
} }
/**
* Selects single node for single selector and appends it to the results.
*/
protected void selectAndAdd(Node node, CssSelector cssSelector, LinkedList<Node> result) {
// ignore all nodes that are not elements
if (node.getNodeType() != Node.NodeType.ELEMENT) {
return;
}
boolean matched = cssSelector.accept(node);
if (matched) {
// check for duplicates
if (result.contains(node)) {
return;
}
// no duplicate found, add it to the results
result.add(node);
}
}
/**
* Filter nodes.
*/
protected boolean filter(LinkedList<Node> currentResults, Node node, CssSelector cssSelector, int index) {
return cssSelector.accept(currentResults, node, index);
}
}
|
Add a select method that accept pre-compiled css selectors
|
jodd-lagarto/src/main/java/jodd/lagarto/dom/NodeSelector.java
|
Add a select method that accept pre-compiled css selectors
|
<ide><path>odd-lagarto/src/main/java/jodd/lagarto/dom/NodeSelector.java
<ide>
<ide> List<CssSelector> selectors = csselly.parse();
<ide>
<del> List<Node> selectedNodes = select(rootNode, selectors);
<del>
<del> for (Node selectedNode : selectedNodes) {
<del> if (results.contains(selectedNode) == false) {
<add> for (Node selectedNode : select(rootNode, selectors)) {
<add> if (!results.contains(selectedNode)) {
<add> results.add(selectedNode);
<add> }
<add> }
<add> }
<add> return results;
<add> }
<add>
<add> public LinkedList<Node> select(List<List<CssSelector>> selectorsList) {
<add>
<add> LinkedList<Node> results = new LinkedList<Node>();
<add>
<add> for (List<CssSelector> selectors : selectorsList) {
<add>
<add> for (Node selectedNode : select(rootNode, selectors)) {
<add> if (!results.contains(selectedNode)) {
<ide> results.add(selectedNode);
<ide> }
<ide> }
|
|
Java
|
bsd-3-clause
|
26a47d172fccc7ca2401c195d3a0ac8ab4f98790
| 0 |
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
|
/*
* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.asm.hsail;
import static com.oracle.graal.api.code.MemoryBarriers.*;
import static com.oracle.graal.api.code.ValueUtil.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.hsail.*;
/**
* This class contains routines to emit HSAIL assembly code.
*/
public abstract class HSAILAssembler extends AbstractHSAILAssembler {
/**
* Stack size in bytes (used to keep track of spilling).
*/
private int maxDataTypeSize;
/**
* Maximum stack offset used by a store operation.
*/
private long maxStackOffset = 0;
public long upperBoundStackSize() {
return maxStackOffset + maxDataTypeSize;
}
public HSAILAssembler(TargetDescription target) {
super(target);
}
@Override
public HSAILAddress makeAddress(Register base, int displacement) {
return new HSAILAddress(base, displacement);
}
@Override
public HSAILAddress getPlaceholder() {
return null;
}
@Override
public final void ensureUniquePC() {
throw GraalInternalError.unimplemented();
}
public final void undefined(String str) {
emitString("undefined operation " + str);
}
public final void exit() {
emitString("ret;" + "");
}
/**
* Moves an Object into a register.
*
* Because Object references become stale after Garbage collection (GC) the technique used here
* is to load a JNI global reference to that Object into the register. These JNI global
* references get updated by the GC whenever the GC moves an Object.
*
* @param a the destination register
* @param src the Object Constant being moved
*/
public abstract void mov(Register a, Constant src);
private static String getBitTypeFromKind(Kind kind) {
switch (kind) {
case Boolean:
case Byte:
case Short:
case Char:
case Int:
case Float:
return "b32";
case Long:
case Double:
case Object:
return "b64";
default:
throw GraalInternalError.shouldNotReachHere();
}
}
public final void emitMov(Kind kind, Value dst, Value src) {
if (isRegister(dst) && isConstant(src) && kind.getStackKind() == Kind.Object) {
mov(asRegister(dst), asConstant(src));
} else {
String argtype = getBitTypeFromKind(kind);
emitString("mov_" + argtype + " " + mapRegOrConstToString(dst) + ", " + mapRegOrConstToString(src) + ";");
}
}
private void emitAddrOp(String instr, Value reg, HSAILAddress addr) {
String storeValue = mapRegOrConstToString(reg);
emitString(instr + " " + storeValue + ", " + mapAddress(addr) + ";");
}
/**
* Emits a memory barrier instruction.
*
* @param barriers the kind of barrier to emit
*/
public final void emitMembar(int barriers) {
if (barriers == 0) {
emitString("// no barrier before volatile read");
} else if (barriers == JMM_POST_VOLATILE_READ) {
emitString("sync; // barriers=" + MemoryBarriers.barriersString(barriers));
} else if (barriers == JMM_PRE_VOLATILE_WRITE) {
emitString("sync; // barriers=" + MemoryBarriers.barriersString(barriers));
} else if (barriers == JMM_POST_VOLATILE_WRITE) {
emitString("sync; // barriers=" + MemoryBarriers.barriersString(barriers));
}
}
public final void emitLoad(Kind kind, Value dest, HSAILAddress addr) {
emitLoad(dest, addr, getArgTypeFromKind(kind));
}
public final void emitLoad(Value dest, HSAILAddress addr, String argTypeStr) {
emitAddrOp("ld_global_" + argTypeStr, dest, addr);
}
public final void emitLda(Value dest, HSAILAddress addr) {
emitAddrOp("lda_global_u64", dest, addr);
}
public final void emitLea(Value dest, HSAILAddress addr) {
String prefix = getArgType(dest);
emitString(String.format("add_%s %s, $%s, 0x%s;", prefix, HSAIL.mapRegister(dest), addr.getBase().name, Long.toHexString(addr.getDisplacement())));
}
public final void emitLoadKernelArg(Value dest, String kernArgName, String argTypeStr) {
emitString("ld_kernarg_" + argTypeStr + " " + HSAIL.mapRegister(dest) + ", [" + kernArgName + "];");
}
public final void emitStore(Kind kind, Value src, HSAILAddress addr) {
emitStore(src, addr, getArgTypeFromKind(kind));
}
public final void emitStore(Value dest, HSAILAddress addr, String argTypeStr) {
emitAddrOp("st_global_" + argTypeStr, dest, addr);
}
private void storeImmediateImpl(String storeType, String value, HSAILAddress addr) {
emitString("st_global_" + storeType + " " + value + ", " + mapAddress(addr) + ";");
}
public final void emitStoreImmediate(Kind kind, long src, HSAILAddress addr) {
assert (kind != Kind.Float && kind != Kind.Double);
storeImmediateImpl(getArgTypeFromKind(kind), Long.toString(src), addr);
}
public final void emitStoreImmediate(float src, HSAILAddress addr) {
storeImmediateImpl("f32", floatToString(src), addr);
}
public final void emitStoreImmediate(double src, HSAILAddress addr) {
storeImmediateImpl("f64", doubleToString(src), addr);
}
public final void emitSpillLoad(Kind kind, Value dest, Value src) {
emitString("ld_spill_" + getArgTypeFromKind(kind) + " " + HSAIL.mapRegister(dest) + ", " + mapStackSlot(src, getArgSizeFromKind(kind)) + ";");
}
public final void emitStore(Value src, HSAILAddress addr) {
emitString("st_global_" + getArgType(src) + " " + HSAIL.mapRegister(src) + ", " + mapAddress(addr) + ";");
}
public final void emitSpillStore(Kind kind, Value src, Value dest) {
int sizestored = getArgSizeFromKind(kind);
if (maxDataTypeSize < sizestored) {
maxDataTypeSize = sizestored;
}
int stackoffset = HSAIL.getStackOffset(dest);
if (maxStackOffset < stackoffset) {
maxStackOffset = stackoffset;
}
emitString("st_spill_" + getArgTypeFromKind(kind) + " " + HSAIL.mapRegister(src) + ", " + mapStackSlot(dest, getArgSizeFromKind(kind)) + ";");
}
public static String mapStackSlot(Value reg, int argSize) {
long startOffset = HSAIL.getStackOffsetStart(reg, argSize);
return "[%spillseg]" + "[" + startOffset + "]";
}
public void cbr(String target1) {
emitString("cbr " + "$c0" + ", " + target1 + ";");
}
public int getArgSize(Value src) {
return getArgSizeFromKind(src.getKind());
}
private static int getArgSizeFromKind(Kind kind) {
switch (kind) {
case Int:
case Float:
return 32;
case Double:
case Long:
case Object:
return 64;
default:
throw GraalInternalError.shouldNotReachHere();
}
}
private static String getArgType(Value src) {
return getArgTypeFromKind(src.getKind());
}
private static String getArgTypeFromKind(Kind kind) {
String prefix = "";
switch (kind) {
case Float:
prefix = "f32";
break;
case Double:
prefix = "f64";
break;
case Int:
prefix = "s32";
break;
case Long:
prefix = "s64";
break;
case Object:
prefix = "u64";
break;
case Char:
prefix = "u16";
break;
case Short:
prefix = "s16";
break;
case Byte:
prefix = "s8";
break;
case Boolean:
prefix = "u8";
break;
default:
throw GraalInternalError.shouldNotReachHere();
}
return prefix;
}
public static final String getArgTypeForceUnsigned(Value src) {
return getArgTypeForceUnsignedKind(src.getKind());
}
public static final String getArgTypeForceUnsignedKind(Kind kind) {
switch (kind) {
case Int:
return "u32";
case Long:
case Object:
return "u64";
default:
throw GraalInternalError.shouldNotReachHere();
}
}
public static final String getArgTypeBitwiseLogical(Value src) {
String length = getArgType(src);
String prefix = "_b" + (length.endsWith("64") ? "64" : "32");
return prefix;
}
/**
* Emits a compare instruction.
*
* @param src0 - the first source register
* @param src1 - the second source register
* @param condition - the compare condition i.e., eq, ne, lt, gt
* @param unordered - flag specifying if this is an unordered compare. This only applies to
* float compares.
* @param isUnsignedCompare - flag specifying if this is a compare of unsigned values.
*/
public void emitCompare(Kind compareKind, Value src0, Value src1, String condition, boolean unordered, boolean isUnsignedCompare) {
// Formulate the prefix of the instruction.
// if unordered is true, it should be ignored unless the src type is f32 or f64
String argType = getArgTypeFromKind(compareKind);
String unorderedPrefix = (argType.startsWith("f") && unordered ? "u" : "");
String prefix = "cmp_" + condition + unorderedPrefix + "_b1_" + (isUnsignedCompare ? getArgTypeForceUnsigned(src1) : argType);
// Generate a comment for debugging purposes
String comment = (isConstant(src1) && (src1.getKind() == Kind.Object) && (asConstant(src1).isNull()) ? " // null test " : "");
// Emit the instruction.
emitString(prefix + " $c0, " + mapRegOrConstToString(src0) + ", " + mapRegOrConstToString(src1) + ";" + comment);
}
public void emitConvert(Value dest, Value src, String destType, String srcType) {
String prefix = "cvt_";
if (destType.equals("f32") && srcType.equals("f64")) {
prefix = "cvt_near_";
} else if (srcType.startsWith("f") && (destType.startsWith("s") || destType.startsWith("u"))) {
prefix = "cvt_zeroi_sat_";
}
emitString(prefix + destType + "_" + srcType + " " + HSAIL.mapRegister(dest) + ", " + HSAIL.mapRegister(src) + ";");
}
public void emitConvert(Value dest, Value src, Kind destKind, Kind srcKind) {
String destType = getArgTypeFromKind(destKind);
String srcType = getArgTypeFromKind(srcKind);
emitConvert(dest, src, destType, srcType);
}
/**
* Emits a convert instruction that uses unsigned prefix, regardless of the type of dest and
* src.
*
* @param dest the destination operand
* @param src the source operand
*/
public void emitConvertForceUnsigned(Value dest, Value src) {
emitString("cvt_" + getArgTypeForceUnsigned(dest) + "_" + getArgTypeForceUnsigned(src) + " " + HSAIL.mapRegister(dest) + ", " + HSAIL.mapRegister(src) + ";");
}
public static String mapAddress(HSAILAddress addr) {
if (addr.getBase().encoding() < 0) {
return "[0x" + Long.toHexString(addr.getDisplacement()) + "]";
} else {
return "[$d" + addr.getBase().encoding() + " + " + addr.getDisplacement() + "]";
}
}
private static String doubleToString(double dval) {
long lval = Double.doubleToRawLongBits(dval);
long lvalIgnoreSign = lval & 0x7fffffffffffffffL;
if (lvalIgnoreSign >= 0x7ff0000000000000L) {
return "0D" + String.format("%16x", lval);
} else {
return Double.toString(dval);
}
}
private static String floatToString(float fval) {
int ival = Float.floatToRawIntBits(fval);
int ivalIgnoreSign = ival & 0x7fffffff;
if (ivalIgnoreSign >= 0x7f800000) {
return "0F" + String.format("%8x", ival);
} else {
return Float.toString(fval) + "f";
}
}
private static String mapRegOrConstToString(Value src) {
if (!isConstant(src)) {
return HSAIL.mapRegister(src);
} else {
Constant consrc = asConstant(src);
switch (src.getKind()) {
case Boolean:
case Int:
return Integer.toString(consrc.asInt());
case Float:
return floatToString(consrc.asFloat());
case Double:
return doubleToString(consrc.asDouble());
case Long:
return "0x" + Long.toHexString(consrc.asLong());
case Object:
if (consrc.isNull()) {
return "0";
} else {
throw GraalInternalError.shouldNotReachHere("unknown type: " + src);
}
default:
throw GraalInternalError.shouldNotReachHere("unknown type: " + src);
}
}
}
/**
* Emits an instruction.
*
* @param mnemonic the instruction mnemonic
* @param dest the destination operand
* @param sources the source operands
*/
public final void emit(String mnemonic, Value dest, Value... sources) {
String prefix = getArgType(dest);
emitTextFormattedInstruction(mnemonic + "_" + prefix, dest, sources);
}
/**
* Emits an unsigned instruction.
*
* @param mnemonic the instruction mnemonic
* @param dest the destination argument
* @param sources the source arguments
*
*/
public final void emitForceUnsigned(String mnemonic, Value dest, Value... sources) {
String prefix = getArgTypeForceUnsigned(dest);
emitTextFormattedInstruction(mnemonic + "_" + prefix, dest, sources);
}
public final void emitForceUnsignedKind(String mnemonic, Kind kind, Value dest, Value... sources) {
String prefix = getArgTypeForceUnsignedKind(kind);
emitTextFormattedInstruction(mnemonic + "_" + prefix, dest, sources);
}
/**
* Emits an instruction for a bitwise logical operation.
*
* @param mnemonic the instruction mnemonic
* @param dest the destination
* @param sources the source operands
*/
public final void emitForceBitwise(String mnemonic, Value dest, Value... sources) {
String prefix = getArgTypeBitwiseLogical(dest);
emitTextFormattedInstruction(mnemonic + prefix, dest, sources);
}
/**
* Central helper routine that emits a text formatted HSAIL instruction via call to
* AbstractAssembler.emitString. All the emit routines in the assembler end up calling this one.
*
* @param instr the full instruction mnenomics including any prefixes
* @param dest the destination operand
* @param sources the source operand
*/
private void emitTextFormattedInstruction(String instr, Value dest, Value... sources) {
/**
* Destination can't be a constant and no instruction has > 3 source operands.
*/
assert (!isConstant(dest) && sources.length <= 3);
switch (sources.length) {
case 3:
// Emit an instruction with three source operands.
emitString(String.format("%s %s, %s, %s, %s;", instr, HSAIL.mapRegister(dest), mapRegOrConstToString(sources[0]), mapRegOrConstToString(sources[1]), mapRegOrConstToString(sources[2])));
break;
case 2:
// Emit an instruction with two source operands.
emitString(String.format("%s %s, %s, %s;", instr, HSAIL.mapRegister(dest), mapRegOrConstToString(sources[0]), mapRegOrConstToString(sources[1])));
break;
case 1:
// Emit an instruction with one source operand.
emitString(String.format("%s %s, %s;", instr, HSAIL.mapRegister(dest), mapRegOrConstToString(sources[0])));
break;
default:
// Emit an instruction with one source operand.
emitString(String.format("%s %s;", instr, HSAIL.mapRegister(dest)));
break;
}
}
/**
* Emits a conditional move instruction.
*
* @param dest the destination operand storing result of the move
* @param trueReg the register that should be copied to dest if the condition is true
* @param falseReg the register that should be copied to dest if the condition is false
* @param width the width of the instruction (32 or 64 bits)
*/
public final void emitConditionalMove(Value dest, Value trueReg, Value falseReg, int width) {
assert (!isConstant(dest));
String instr = (width == 32 ? "cmov_b32" : "cmov_b64");
emitString(String.format("%s %s, %s%s, %s;", instr, HSAIL.mapRegister(dest), "$c0, ", mapRegOrConstToString(trueReg), mapRegOrConstToString(falseReg)));
}
/**
* Emits code to build a 64-bit pointer from a compressed value and the associated base and
* shift. The compressed value could represent either a normal oop or a klass ptr. If the
* compressed value is 0, the uncompressed must also be 0. We only emit this if base and shift
* are not both zero.
*
* @param result the register containing the compressed value on input and the uncompressed ptr
* on output
* @param base the amount to be added to the compressed value
* @param shift the number of bits to shift left the compressed value
* @param testForNull true if the compressed value might be null
*/
public void emitCompressedOopDecode(Value result, long base, int shift, boolean testForNull) {
assert (base != 0 || shift != 0);
assert (!isConstant(result));
if (base == 0) {
// we don't have to test for null if shl is the only operation
emitForceUnsignedKind("shl", Kind.Long, result, result, Constant.forInt(shift));
} else if (shift == 0) {
// only use add if result is not starting as null (test only if testForNull is true)
emitWithOptionalTestForNull(testForNull, "add", result, result, Constant.forLong(base));
} else {
// only use mad if result is not starting as null (test only if testForNull is true)
emitWithOptionalTestForNull(testForNull, "mad", result, result, Constant.forInt(1 << shift), Constant.forLong(base));
}
}
/**
* Emits code to build a compressed value from a full 64-bit pointer using the associated base
* and shift. The compressed value could represent either a normal oop or a klass ptr. If the
* ptr is 0, the compressed value must also be 0. We only emit this if base and shift are not
* both zero.
*
* @param result the register containing the 64-bit pointer on input and the compressed value on
* output
* @param base the amount to be subtracted from the 64-bit pointer
* @param shift the number of bits to shift right the 64-bit pointer
* @param testForNull true if the 64-bit pointer might be null
*/
public void emitCompressedOopEncode(Value result, long base, int shift, boolean testForNull) {
assert (base != 0 || shift != 0);
assert (!isConstant(result));
if (base != 0) {
// only use sub if result is not starting as null (test only if testForNull is true)
emitWithOptionalTestForNull(testForNull, "sub", result, result, Constant.forLong(base));
}
if (shift != 0) {
// note that the shr can still be done even if the result is null
emitForceUnsignedKind("shr", Kind.Long, result, result, Constant.forInt(shift));
}
}
/**
* Emits code for the requested mnemonic on the result and sources. In addition, if testForNull
* is true, surrounds the instruction with code that will guarantee that if the result starts as
* 0, it will remain 0.
*
* @param testForNull true if we want to add the code to check for and preserve null
* @param mnemonic the instruction to be applied (without size prefix)
* @param result the register which is both an input and the final output
* @param sources the sources for the mnemonic instruction
*/
private void emitWithOptionalTestForNull(boolean testForNull, String mnemonic, Value result, Value... sources) {
if (testForNull) {
emitCompare(Kind.Long, result, Constant.forLong(0), "eq", false, true);
}
emitForceUnsigned(mnemonic, result, sources);
if (testForNull) {
emitConditionalMove(result, Constant.forLong(0), result, 64);
}
}
/**
* Emits an atomic_cas_global instruction.
*
* @param result result operand that gets the original contents of the memory location
* @param address the memory location
* @param cmpValue the value that will be compared against the memory location
* @param newValue the new value that will be written to the memory location if the cmpValue
* comparison matches
*/
public void emitAtomicCas(Kind accessKind, AllocatableValue result, HSAILAddress address, Value cmpValue, Value newValue) {
emitString(String.format("atomic_cas_global_b%d %s, %s, %s, %s;", getArgSizeFromKind(accessKind), HSAIL.mapRegister(result), mapAddress(address), mapRegOrConstToString(cmpValue),
mapRegOrConstToString(newValue)));
}
/**
* Emits an atomic_add_global instruction.
*
* @param result result operand that gets the original contents of the memory location
* @param address the memory location
* @param delta the amount to add
*/
public void emitAtomicAdd(AllocatableValue result, HSAILAddress address, Value delta) {
// ensure result and delta agree (this should probably be at some higher level)
Value mydelta = delta;
if (!isConstant(delta) && (getArgSize(result) != getArgSize(delta))) {
emitConvert(result, delta, result.getKind(), delta.getKind());
mydelta = result;
}
String prefix = getArgTypeForceUnsigned(result);
emitString(String.format("atomic_add_global_%s %s, %s, %s;", prefix, HSAIL.mapRegister(result), mapAddress(address), mapRegOrConstToString(mydelta)));
}
/**
* Emits an atomic_exch_global instruction.
*
* @param result result operand that gets the original contents of the memory location
* @param address the memory location
* @param newValue the new value to write to the memory location
*/
public void emitAtomicExch(Kind accessKind, AllocatableValue result, HSAILAddress address, Value newValue) {
emitString(String.format("atomic_exch_global_b%d %s, %s, %s;", getArgSizeFromKind(accessKind), HSAIL.mapRegister(result), mapAddress(address), mapRegOrConstToString(newValue)));
}
/**
* Emits a comment. Useful for debugging purposes.
*
* @param comment
*/
public void emitComment(String comment) {
emitString(comment);
}
public String getDeoptInfoName() {
return "%_deoptInfo";
}
public String getDeoptLabelName() {
return "@L_Deopt";
}
public void emitWorkItemAbsId(Value dest) {
emitString(String.format("workitemabsid_u32 %s, 0;", HSAIL.mapRegister(dest)));
}
public void emitCuId(Value dest) {
emitString(String.format("cuid_u32 %s;", HSAIL.mapRegister(dest)));
}
public void emitLaneId(Value dest) {
emitString(String.format("laneid_u32 %s;", HSAIL.mapRegister(dest)));
}
public void emitWaveId(Value dest) {
emitString(String.format("waveid_u32 %s;", HSAIL.mapRegister(dest)));
}
public void emitMaxWaveId(Value dest) {
// emitString(String.format("maxwaveid_u32 %s;", HSAIL.mapRegister(dest)));
int hardCodedMaxWaveId = 36;
emitComment("// Hard-coded maxwaveid=" + hardCodedMaxWaveId + " until it works");
emitMov(Kind.Int, dest, Constant.forInt(hardCodedMaxWaveId));
}
public void emitMultiplyByWavesize(Value dest) {
String regName = HSAIL.mapRegister(dest);
emitString(String.format("mul_u%d %s, %s, WAVESIZE;", getArgSize(dest), regName, regName));
}
public void emitGetWavesize(Value dest) {
String regName = HSAIL.mapRegister(dest);
emitString(String.format("mov_b%d %s, WAVESIZE;", getArgSize(dest), regName));
}
public void emitLoadAcquire(Value dest, HSAILAddress address) {
emitString(String.format("ld_global_acq_u%d %s, %s;", getArgSize(dest), HSAIL.mapRegister(dest), mapAddress(address)));
}
public void emitStoreRelease(Value src, HSAILAddress address) {
emitString(String.format("st_global_rel_u%d %s, %s;", getArgSize(src), HSAIL.mapRegister(src), mapAddress(address)));
}
}
|
graal/com.oracle.graal.asm.hsail/src/com/oracle/graal/asm/hsail/HSAILAssembler.java
|
/*
* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.asm.hsail;
import static com.oracle.graal.api.code.MemoryBarriers.*;
import static com.oracle.graal.api.code.ValueUtil.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.hsail.*;
/**
* This class contains routines to emit HSAIL assembly code.
*/
public abstract class HSAILAssembler extends AbstractHSAILAssembler {
/**
* Stack size in bytes (used to keep track of spilling).
*/
private int maxDataTypeSize;
/**
* Maximum stack offset used by a store operation.
*/
private long maxStackOffset = 0;
public long upperBoundStackSize() {
return maxStackOffset + maxDataTypeSize;
}
public HSAILAssembler(TargetDescription target) {
super(target);
}
@Override
public HSAILAddress makeAddress(Register base, int displacement) {
return new HSAILAddress(base, displacement);
}
@Override
public HSAILAddress getPlaceholder() {
return null;
}
@Override
public final void ensureUniquePC() {
throw GraalInternalError.unimplemented();
}
public final void undefined(String str) {
emitString("undefined operation " + str);
}
public final void exit() {
emitString("ret;" + "");
}
/**
* Moves an Object into a register.
*
* Because Object references become stale after Garbage collection (GC) the technique used here
* is to load a JNI global reference to that Object into the register. These JNI global
* references get updated by the GC whenever the GC moves an Object.
*
* @param a the destination register
* @param src the Object Constant being moved
*/
public abstract void mov(Register a, Constant src);
public final void emitMov(Kind kind, Value dst, Value src) {
if (isRegister(dst) && isConstant(src) && kind.getStackKind() == Kind.Object) {
mov(asRegister(dst), asConstant(src));
} else {
String argtype = getArgTypeFromKind(kind).substring(1);
emitString("mov_b" + argtype + " " + mapRegOrConstToString(dst) + ", " + mapRegOrConstToString(src) + ";");
}
}
private void emitAddrOp(String instr, Value reg, HSAILAddress addr) {
String storeValue = mapRegOrConstToString(reg);
emitString(instr + " " + storeValue + ", " + mapAddress(addr) + ";");
}
/**
* Emits a memory barrier instruction.
*
* @param barriers the kind of barrier to emit
*/
public final void emitMembar(int barriers) {
if (barriers == 0) {
emitString("// no barrier before volatile read");
} else if (barriers == JMM_POST_VOLATILE_READ) {
emitString("sync; // barriers=" + MemoryBarriers.barriersString(barriers));
} else if (barriers == JMM_PRE_VOLATILE_WRITE) {
emitString("sync; // barriers=" + MemoryBarriers.barriersString(barriers));
} else if (barriers == JMM_POST_VOLATILE_WRITE) {
emitString("sync; // barriers=" + MemoryBarriers.barriersString(barriers));
}
}
public final void emitLoad(Kind kind, Value dest, HSAILAddress addr) {
emitLoad(dest, addr, getArgTypeFromKind(kind));
}
public final void emitLoad(Value dest, HSAILAddress addr, String argTypeStr) {
emitAddrOp("ld_global_" + argTypeStr, dest, addr);
}
public final void emitLda(Value dest, HSAILAddress addr) {
emitAddrOp("lda_global_u64", dest, addr);
}
public final void emitLea(Value dest, HSAILAddress addr) {
String prefix = getArgType(dest);
emitString(String.format("add_%s %s, $%s, 0x%s;", prefix, HSAIL.mapRegister(dest), addr.getBase().name, Long.toHexString(addr.getDisplacement())));
}
public final void emitLoadKernelArg(Value dest, String kernArgName, String argTypeStr) {
emitString("ld_kernarg_" + argTypeStr + " " + HSAIL.mapRegister(dest) + ", [" + kernArgName + "];");
}
public final void emitStore(Kind kind, Value src, HSAILAddress addr) {
emitStore(src, addr, getArgTypeFromKind(kind));
}
public final void emitStore(Value dest, HSAILAddress addr, String argTypeStr) {
emitAddrOp("st_global_" + argTypeStr, dest, addr);
}
private void storeImmediateImpl(String storeType, String value, HSAILAddress addr) {
emitString("st_global_" + storeType + " " + value + ", " + mapAddress(addr) + ";");
}
public final void emitStoreImmediate(Kind kind, long src, HSAILAddress addr) {
assert (kind != Kind.Float && kind != Kind.Double);
storeImmediateImpl(getArgTypeFromKind(kind), Long.toString(src), addr);
}
public final void emitStoreImmediate(float src, HSAILAddress addr) {
storeImmediateImpl("f32", floatToString(src), addr);
}
public final void emitStoreImmediate(double src, HSAILAddress addr) {
storeImmediateImpl("f64", doubleToString(src), addr);
}
public final void emitSpillLoad(Kind kind, Value dest, Value src) {
emitString("ld_spill_" + getArgTypeFromKind(kind) + " " + HSAIL.mapRegister(dest) + ", " + mapStackSlot(src, getArgSizeFromKind(kind)) + ";");
}
public final void emitStore(Value src, HSAILAddress addr) {
emitString("st_global_" + getArgType(src) + " " + HSAIL.mapRegister(src) + ", " + mapAddress(addr) + ";");
}
public final void emitSpillStore(Kind kind, Value src, Value dest) {
int sizestored = getArgSizeFromKind(kind);
if (maxDataTypeSize < sizestored) {
maxDataTypeSize = sizestored;
}
int stackoffset = HSAIL.getStackOffset(dest);
if (maxStackOffset < stackoffset) {
maxStackOffset = stackoffset;
}
emitString("st_spill_" + getArgTypeFromKind(kind) + " " + HSAIL.mapRegister(src) + ", " + mapStackSlot(dest, getArgSizeFromKind(kind)) + ";");
}
public static String mapStackSlot(Value reg, int argSize) {
long startOffset = HSAIL.getStackOffsetStart(reg, argSize);
return "[%spillseg]" + "[" + startOffset + "]";
}
public void cbr(String target1) {
emitString("cbr " + "$c0" + ", " + target1 + ";");
}
public int getArgSize(Value src) {
return getArgSizeFromKind(src.getKind());
}
private static int getArgSizeFromKind(Kind kind) {
switch (kind) {
case Int:
case Float:
return 32;
case Double:
case Long:
case Object:
return 64;
default:
throw GraalInternalError.shouldNotReachHere();
}
}
private static String getArgType(Value src) {
return getArgTypeFromKind(src.getKind());
}
private static String getArgTypeFromKind(Kind kind) {
String prefix = "";
switch (kind) {
case Float:
prefix = "f32";
break;
case Double:
prefix = "f64";
break;
case Int:
prefix = "s32";
break;
case Long:
prefix = "s64";
break;
case Object:
prefix = "u64";
break;
case Char:
prefix = "u16";
break;
case Short:
prefix = "s16";
break;
case Byte:
prefix = "s8";
break;
case Boolean:
prefix = "u8";
break;
default:
throw GraalInternalError.shouldNotReachHere();
}
return prefix;
}
public static final String getArgTypeForceUnsigned(Value src) {
return getArgTypeForceUnsignedKind(src.getKind());
}
public static final String getArgTypeForceUnsignedKind(Kind kind) {
switch (kind) {
case Int:
return "u32";
case Long:
case Object:
return "u64";
default:
throw GraalInternalError.shouldNotReachHere();
}
}
public static final String getArgTypeBitwiseLogical(Value src) {
String length = getArgType(src);
String prefix = "_b" + (length.endsWith("64") ? "64" : "32");
return prefix;
}
/**
* Emits a compare instruction.
*
* @param src0 - the first source register
* @param src1 - the second source register
* @param condition - the compare condition i.e., eq, ne, lt, gt
* @param unordered - flag specifying if this is an unordered compare. This only applies to
* float compares.
* @param isUnsignedCompare - flag specifying if this is a compare of unsigned values.
*/
public void emitCompare(Kind compareKind, Value src0, Value src1, String condition, boolean unordered, boolean isUnsignedCompare) {
// Formulate the prefix of the instruction.
// if unordered is true, it should be ignored unless the src type is f32 or f64
String argType = getArgTypeFromKind(compareKind);
String unorderedPrefix = (argType.startsWith("f") && unordered ? "u" : "");
String prefix = "cmp_" + condition + unorderedPrefix + "_b1_" + (isUnsignedCompare ? getArgTypeForceUnsigned(src1) : argType);
// Generate a comment for debugging purposes
String comment = (isConstant(src1) && (src1.getKind() == Kind.Object) && (asConstant(src1).isNull()) ? " // null test " : "");
// Emit the instruction.
emitString(prefix + " $c0, " + mapRegOrConstToString(src0) + ", " + mapRegOrConstToString(src1) + ";" + comment);
}
public void emitConvert(Value dest, Value src, String destType, String srcType) {
String prefix = "cvt_";
if (destType.equals("f32") && srcType.equals("f64")) {
prefix = "cvt_near_";
} else if (srcType.startsWith("f") && (destType.startsWith("s") || destType.startsWith("u"))) {
prefix = "cvt_zeroi_sat_";
}
emitString(prefix + destType + "_" + srcType + " " + HSAIL.mapRegister(dest) + ", " + HSAIL.mapRegister(src) + ";");
}
public void emitConvert(Value dest, Value src, Kind destKind, Kind srcKind) {
String destType = getArgTypeFromKind(destKind);
String srcType = getArgTypeFromKind(srcKind);
emitConvert(dest, src, destType, srcType);
}
/**
* Emits a convert instruction that uses unsigned prefix, regardless of the type of dest and
* src.
*
* @param dest the destination operand
* @param src the source operand
*/
public void emitConvertForceUnsigned(Value dest, Value src) {
emitString("cvt_" + getArgTypeForceUnsigned(dest) + "_" + getArgTypeForceUnsigned(src) + " " + HSAIL.mapRegister(dest) + ", " + HSAIL.mapRegister(src) + ";");
}
public static String mapAddress(HSAILAddress addr) {
if (addr.getBase().encoding() < 0) {
return "[0x" + Long.toHexString(addr.getDisplacement()) + "]";
} else {
return "[$d" + addr.getBase().encoding() + " + " + addr.getDisplacement() + "]";
}
}
private static String doubleToString(double dval) {
long lval = Double.doubleToRawLongBits(dval);
long lvalIgnoreSign = lval & 0x7fffffffffffffffL;
if (lvalIgnoreSign >= 0x7ff0000000000000L) {
return "0D" + String.format("%16x", lval);
} else {
return Double.toString(dval);
}
}
private static String floatToString(float fval) {
int ival = Float.floatToRawIntBits(fval);
int ivalIgnoreSign = ival & 0x7fffffff;
if (ivalIgnoreSign >= 0x7f800000) {
return "0F" + String.format("%8x", ival);
} else {
return Float.toString(fval) + "f";
}
}
private static String mapRegOrConstToString(Value src) {
if (!isConstant(src)) {
return HSAIL.mapRegister(src);
} else {
Constant consrc = asConstant(src);
switch (src.getKind()) {
case Boolean:
case Int:
return Integer.toString(consrc.asInt());
case Float:
return floatToString(consrc.asFloat());
case Double:
return doubleToString(consrc.asDouble());
case Long:
return "0x" + Long.toHexString(consrc.asLong());
case Object:
if (consrc.isNull()) {
return "0";
} else {
throw GraalInternalError.shouldNotReachHere("unknown type: " + src);
}
default:
throw GraalInternalError.shouldNotReachHere("unknown type: " + src);
}
}
}
/**
* Emits an instruction.
*
* @param mnemonic the instruction mnemonic
* @param dest the destination operand
* @param sources the source operands
*/
public final void emit(String mnemonic, Value dest, Value... sources) {
String prefix = getArgType(dest);
emitTextFormattedInstruction(mnemonic + "_" + prefix, dest, sources);
}
/**
* Emits an unsigned instruction.
*
* @param mnemonic the instruction mnemonic
* @param dest the destination argument
* @param sources the source arguments
*
*/
public final void emitForceUnsigned(String mnemonic, Value dest, Value... sources) {
String prefix = getArgTypeForceUnsigned(dest);
emitTextFormattedInstruction(mnemonic + "_" + prefix, dest, sources);
}
public final void emitForceUnsignedKind(String mnemonic, Kind kind, Value dest, Value... sources) {
String prefix = getArgTypeForceUnsignedKind(kind);
emitTextFormattedInstruction(mnemonic + "_" + prefix, dest, sources);
}
/**
* Emits an instruction for a bitwise logical operation.
*
* @param mnemonic the instruction mnemonic
* @param dest the destination
* @param sources the source operands
*/
public final void emitForceBitwise(String mnemonic, Value dest, Value... sources) {
String prefix = getArgTypeBitwiseLogical(dest);
emitTextFormattedInstruction(mnemonic + prefix, dest, sources);
}
/**
* Central helper routine that emits a text formatted HSAIL instruction via call to
* AbstractAssembler.emitString. All the emit routines in the assembler end up calling this one.
*
* @param instr the full instruction mnenomics including any prefixes
* @param dest the destination operand
* @param sources the source operand
*/
private void emitTextFormattedInstruction(String instr, Value dest, Value... sources) {
/**
* Destination can't be a constant and no instruction has > 3 source operands.
*/
assert (!isConstant(dest) && sources.length <= 3);
switch (sources.length) {
case 3:
// Emit an instruction with three source operands.
emitString(String.format("%s %s, %s, %s, %s;", instr, HSAIL.mapRegister(dest), mapRegOrConstToString(sources[0]), mapRegOrConstToString(sources[1]), mapRegOrConstToString(sources[2])));
break;
case 2:
// Emit an instruction with two source operands.
emitString(String.format("%s %s, %s, %s;", instr, HSAIL.mapRegister(dest), mapRegOrConstToString(sources[0]), mapRegOrConstToString(sources[1])));
break;
case 1:
// Emit an instruction with one source operand.
emitString(String.format("%s %s, %s;", instr, HSAIL.mapRegister(dest), mapRegOrConstToString(sources[0])));
break;
default:
// Emit an instruction with one source operand.
emitString(String.format("%s %s;", instr, HSAIL.mapRegister(dest)));
break;
}
}
/**
* Emits a conditional move instruction.
*
* @param dest the destination operand storing result of the move
* @param trueReg the register that should be copied to dest if the condition is true
* @param falseReg the register that should be copied to dest if the condition is false
* @param width the width of the instruction (32 or 64 bits)
*/
public final void emitConditionalMove(Value dest, Value trueReg, Value falseReg, int width) {
assert (!isConstant(dest));
String instr = (width == 32 ? "cmov_b32" : "cmov_b64");
emitString(String.format("%s %s, %s%s, %s;", instr, HSAIL.mapRegister(dest), "$c0, ", mapRegOrConstToString(trueReg), mapRegOrConstToString(falseReg)));
}
/**
* Emits code to build a 64-bit pointer from a compressed value and the associated base and
* shift. The compressed value could represent either a normal oop or a klass ptr. If the
* compressed value is 0, the uncompressed must also be 0. We only emit this if base and shift
* are not both zero.
*
* @param result the register containing the compressed value on input and the uncompressed ptr
* on output
* @param base the amount to be added to the compressed value
* @param shift the number of bits to shift left the compressed value
* @param testForNull true if the compressed value might be null
*/
public void emitCompressedOopDecode(Value result, long base, int shift, boolean testForNull) {
assert (base != 0 || shift != 0);
assert (!isConstant(result));
if (base == 0) {
// we don't have to test for null if shl is the only operation
emitForceUnsignedKind("shl", Kind.Long, result, result, Constant.forInt(shift));
} else if (shift == 0) {
// only use add if result is not starting as null (test only if testForNull is true)
emitWithOptionalTestForNull(testForNull, "add", result, result, Constant.forLong(base));
} else {
// only use mad if result is not starting as null (test only if testForNull is true)
emitWithOptionalTestForNull(testForNull, "mad", result, result, Constant.forInt(1 << shift), Constant.forLong(base));
}
}
/**
* Emits code to build a compressed value from a full 64-bit pointer using the associated base
* and shift. The compressed value could represent either a normal oop or a klass ptr. If the
* ptr is 0, the compressed value must also be 0. We only emit this if base and shift are not
* both zero.
*
* @param result the register containing the 64-bit pointer on input and the compressed value on
* output
* @param base the amount to be subtracted from the 64-bit pointer
* @param shift the number of bits to shift right the 64-bit pointer
* @param testForNull true if the 64-bit pointer might be null
*/
public void emitCompressedOopEncode(Value result, long base, int shift, boolean testForNull) {
assert (base != 0 || shift != 0);
assert (!isConstant(result));
if (base != 0) {
// only use sub if result is not starting as null (test only if testForNull is true)
emitWithOptionalTestForNull(testForNull, "sub", result, result, Constant.forLong(base));
}
if (shift != 0) {
// note that the shr can still be done even if the result is null
emitForceUnsignedKind("shr", Kind.Long, result, result, Constant.forInt(shift));
}
}
/**
* Emits code for the requested mnemonic on the result and sources. In addition, if testForNull
* is true, surrounds the instruction with code that will guarantee that if the result starts as
* 0, it will remain 0.
*
* @param testForNull true if we want to add the code to check for and preserve null
* @param mnemonic the instruction to be applied (without size prefix)
* @param result the register which is both an input and the final output
* @param sources the sources for the mnemonic instruction
*/
private void emitWithOptionalTestForNull(boolean testForNull, String mnemonic, Value result, Value... sources) {
if (testForNull) {
emitCompare(Kind.Long, result, Constant.forLong(0), "eq", false, true);
}
emitForceUnsigned(mnemonic, result, sources);
if (testForNull) {
emitConditionalMove(result, Constant.forLong(0), result, 64);
}
}
/**
* Emits an atomic_cas_global instruction.
*
* @param result result operand that gets the original contents of the memory location
* @param address the memory location
* @param cmpValue the value that will be compared against the memory location
* @param newValue the new value that will be written to the memory location if the cmpValue
* comparison matches
*/
public void emitAtomicCas(Kind accessKind, AllocatableValue result, HSAILAddress address, Value cmpValue, Value newValue) {
emitString(String.format("atomic_cas_global_b%d %s, %s, %s, %s;", getArgSizeFromKind(accessKind), HSAIL.mapRegister(result), mapAddress(address), mapRegOrConstToString(cmpValue),
mapRegOrConstToString(newValue)));
}
/**
* Emits an atomic_add_global instruction.
*
* @param result result operand that gets the original contents of the memory location
* @param address the memory location
* @param delta the amount to add
*/
public void emitAtomicAdd(AllocatableValue result, HSAILAddress address, Value delta) {
// ensure result and delta agree (this should probably be at some higher level)
Value mydelta = delta;
if (!isConstant(delta) && (getArgSize(result) != getArgSize(delta))) {
emitConvert(result, delta, result.getKind(), delta.getKind());
mydelta = result;
}
String prefix = getArgTypeForceUnsigned(result);
emitString(String.format("atomic_add_global_%s %s, %s, %s;", prefix, HSAIL.mapRegister(result), mapAddress(address), mapRegOrConstToString(mydelta)));
}
/**
* Emits an atomic_exch_global instruction.
*
* @param result result operand that gets the original contents of the memory location
* @param address the memory location
* @param newValue the new value to write to the memory location
*/
public void emitAtomicExch(Kind accessKind, AllocatableValue result, HSAILAddress address, Value newValue) {
emitString(String.format("atomic_exch_global_b%d %s, %s, %s;", getArgSizeFromKind(accessKind), HSAIL.mapRegister(result), mapAddress(address), mapRegOrConstToString(newValue)));
}
/**
* Emits a comment. Useful for debugging purposes.
*
* @param comment
*/
public void emitComment(String comment) {
emitString(comment);
}
public String getDeoptInfoName() {
return "%_deoptInfo";
}
public String getDeoptLabelName() {
return "@L_Deopt";
}
public void emitWorkItemAbsId(Value dest) {
emitString(String.format("workitemabsid_u32 %s, 0;", HSAIL.mapRegister(dest)));
}
public void emitCuId(Value dest) {
emitString(String.format("cuid_u32 %s;", HSAIL.mapRegister(dest)));
}
public void emitLaneId(Value dest) {
emitString(String.format("laneid_u32 %s;", HSAIL.mapRegister(dest)));
}
public void emitWaveId(Value dest) {
emitString(String.format("waveid_u32 %s;", HSAIL.mapRegister(dest)));
}
public void emitMaxWaveId(Value dest) {
// emitString(String.format("maxwaveid_u32 %s;", HSAIL.mapRegister(dest)));
int hardCodedMaxWaveId = 36;
emitComment("// Hard-coded maxwaveid=" + hardCodedMaxWaveId + " until it works");
emitMov(Kind.Int, dest, Constant.forInt(hardCodedMaxWaveId));
}
public void emitMultiplyByWavesize(Value dest) {
String regName = HSAIL.mapRegister(dest);
emitString(String.format("mul_u%d %s, %s, WAVESIZE;", getArgSize(dest), regName, regName));
}
public void emitGetWavesize(Value dest) {
String regName = HSAIL.mapRegister(dest);
emitString(String.format("mov_b%d %s, WAVESIZE;", getArgSize(dest), regName));
}
public void emitLoadAcquire(Value dest, HSAILAddress address) {
emitString(String.format("ld_global_acq_u%d %s, %s;", getArgSize(dest), HSAIL.mapRegister(dest), mapAddress(address)));
}
public void emitStoreRelease(Value src, HSAILAddress address) {
emitString(String.format("st_global_rel_u%d %s, %s;", getArgSize(src), HSAIL.mapRegister(src), mapAddress(address)));
}
}
|
don't generate invalid mov_b hsail instructions
|
graal/com.oracle.graal.asm.hsail/src/com/oracle/graal/asm/hsail/HSAILAssembler.java
|
don't generate invalid mov_b hsail instructions
|
<ide><path>raal/com.oracle.graal.asm.hsail/src/com/oracle/graal/asm/hsail/HSAILAssembler.java
<ide> */
<ide> public abstract void mov(Register a, Constant src);
<ide>
<add> private static String getBitTypeFromKind(Kind kind) {
<add> switch (kind) {
<add> case Boolean:
<add> case Byte:
<add> case Short:
<add> case Char:
<add> case Int:
<add> case Float:
<add> return "b32";
<add> case Long:
<add> case Double:
<add> case Object:
<add> return "b64";
<add> default:
<add> throw GraalInternalError.shouldNotReachHere();
<add> }
<add> }
<add>
<ide> public final void emitMov(Kind kind, Value dst, Value src) {
<ide> if (isRegister(dst) && isConstant(src) && kind.getStackKind() == Kind.Object) {
<ide> mov(asRegister(dst), asConstant(src));
<ide> } else {
<del> String argtype = getArgTypeFromKind(kind).substring(1);
<del> emitString("mov_b" + argtype + " " + mapRegOrConstToString(dst) + ", " + mapRegOrConstToString(src) + ";");
<add> String argtype = getBitTypeFromKind(kind);
<add> emitString("mov_" + argtype + " " + mapRegOrConstToString(dst) + ", " + mapRegOrConstToString(src) + ";");
<ide> }
<ide> }
<ide>
|
|
JavaScript
|
mit
|
d49a7b900472b77d846b7d831dcfaaac1f0392f1
| 0 |
danliris/dl-module,indriHutabalian/dl-module,saidiahmad/dl-module,AndreaZain/dl-module,kristika/dl-module,baguswidypriyono/dl-module
|
require("should");
var SpinningSalesContractDataUtil = require("../../data-util/sales/spinning-sales-contract-data-util");
var helper = require("../../helper");
var validate =require("dl-models").validator.sales.spinningSalesContract;
var moment = require('moment');
var SpinningSalesContractManager = require("../../../src/managers/sales/spinning-sales-contract-manager");
var spinningSalesContractManager = null;
before('#00. connect db', function (done) {
helper.getDb()
.then(db => {
spinningSalesContractManager = new SpinningSalesContractManager(db, {
username: 'dev'
});
done();
})
.catch(e => {
done(e);
});
});
it('#01. should error when create with empty data ', function (done) {
spinningSalesContractManager.create({})
.then(id => {
done("should error when create with empty data");
})
.catch(e => {
try {
e.errors.should.have.property('buyer');
e.errors.should.have.property('quality');
done();
}
catch (ex) {
done(ex);
}
});
});
it('#02. should error when create new data with deliverySchedule less than today', function (done) {
SpinningSalesContractDataUtil.getNewData()
.then(me => {
var dateYesterday = new Date().setDate(new Date().getDate() -1);
me.deliverySchedule = moment(dateYesterday).format('YYYY-MM-DD');
spinningSalesContractManager.create(me)
.then(id => {
done("should error when create new data with deliverySchedule less than today");
})
.catch(e => {
try {
e.errors.should.have.property('deliverySchedule');
done();
}
catch (ex) {
done(ex);
}
});
})
.catch(e => {
done(e);
});
});
it('#03. should error when create new data with shippingQuantityTolerance more than 100', function (done) {
SpinningSalesContractDataUtil.getNewData()
.then(sc => {
sc.shippingQuantityTolerance = 120;
spinningSalesContractManager.create(sc)
.then(id => {
done("should error when create new data with shippingQuantityTolerance more than 100");
})
.catch(e => {
try {
e.errors.should.have.property('shippingQuantityTolerance');
done();
}
catch (ex) {
done(ex);
}
});
})
.catch(e => {
done(e);
});
});
it('#04. should error when create new data with non existent quality, comodity, buyer, accountBank', function (done) {
SpinningSalesContractDataUtil.getNewData()
.then(sc => {
sc.quality._id = '';
sc.comodity._id = '';
sc.buyer._id = '';
sc.accountBank._id = '';
spinningSalesContractManager.create(sc)
.then(id => {
done("should error when create new data with non existent quality, comodity, buyer, accountBank");
})
.catch(e => {
try {
e.errors.should.have.property('quality');
e.errors.should.have.property('comodity');
e.errors.should.have.property('buyer');
e.errors.should.have.property('accountBank');
done();
}
catch (ex) {
done(ex);
}
});
})
.catch(e => {
done(e);
});
});
|
test/sales/spinning-sales-contract/validator.js
|
require("should");
var SpinningSalesContractDataUtil = require("../../data-util/sales/spinning-sales-contract-data-util");
var helper = require("../../helper");
var validate =require("dl-models").validator.sales.spinningSalesContract;
var moment = require('moment');
var SpinningSalesContractManager = require("../../../src/managers/sales/spinning-sales-contract-manager");
var spinningSalesContractManager = null;
before('#00. connect db', function (done) {
helper.getDb()
.then(db => {
spinningSalesContractManager = new SpinningSalesContractManager(db, {
username: 'dev'
});
done();
})
.catch(e => {
done(e);
});
});
it('#01. should error when create with empty data ', function (done) {
spinningSalesContractManager.create({})
.then(id => {
done("should error when create with empty data");
})
.catch(e => {
try {
e.errors.should.have.property('buyer');
e.errors.should.have.property('uom');
e.errors.should.have.property('quality');
done();
}
catch (ex) {
done(ex);
}
});
});
it('#02. should error when create new data with deliverySchedule less than today', function (done) {
SpinningSalesContractDataUtil.getNewData()
.then(me => {
var dateYesterday = new Date().setDate(new Date().getDate() -1);
me.deliverySchedule = moment(dateYesterday).format('YYYY-MM-DD');
spinningSalesContractManager.create(me)
.then(id => {
done("should error when create new data with deliverySchedule less than today");
})
.catch(e => {
try {
e.errors.should.have.property('deliverySchedule');
done();
}
catch (ex) {
done(ex);
}
});
})
.catch(e => {
done(e);
});
});
it('#03. should error when create new data with shippingQuantityTolerance more than 100', function (done) {
SpinningSalesContractDataUtil.getNewData()
.then(sc => {
sc.shippingQuantityTolerance = 120;
spinningSalesContractManager.create(sc)
.then(id => {
done("should error when create new data with shippingQuantityTolerance more than 100");
})
.catch(e => {
try {
e.errors.should.have.property('shippingQuantityTolerance');
done();
}
catch (ex) {
done(ex);
}
});
})
.catch(e => {
done(e);
});
});
it('#04. should error when create new data with non existent quality, comodity, buyer, accountBank,uom', function (done) {
SpinningSalesContractDataUtil.getNewData()
.then(sc => {
sc.quality._id = '';
sc.comodity._id = '';
sc.buyer._id = '';
sc.accountBank._id = '';
sc.uom.unit = '';
spinningSalesContractManager.create(sc)
.then(id => {
done("should error when create new data with non existent quality, comodity, buyer, accountBank, uom");
})
.catch(e => {
try {
e.errors.should.have.property('quality');
e.errors.should.have.property('comodity');
e.errors.should.have.property('buyer');
e.errors.should.have.property('accountBank');
e.errors.should.have.property('uom');
done();
}
catch (ex) {
done(ex);
}
});
})
.catch(e => {
done(e);
});
});
|
update unit test spinning sales contract
|
test/sales/spinning-sales-contract/validator.js
|
update unit test spinning sales contract
|
<ide><path>est/sales/spinning-sales-contract/validator.js
<ide> .catch(e => {
<ide> try {
<ide> e.errors.should.have.property('buyer');
<del> e.errors.should.have.property('uom');
<ide> e.errors.should.have.property('quality');
<ide> done();
<ide> }
<ide> });
<ide> });
<ide>
<del>it('#04. should error when create new data with non existent quality, comodity, buyer, accountBank,uom', function (done) {
<add>it('#04. should error when create new data with non existent quality, comodity, buyer, accountBank', function (done) {
<ide> SpinningSalesContractDataUtil.getNewData()
<ide> .then(sc => {
<ide>
<ide> sc.comodity._id = '';
<ide> sc.buyer._id = '';
<ide> sc.accountBank._id = '';
<del> sc.uom.unit = '';
<ide>
<ide> spinningSalesContractManager.create(sc)
<ide> .then(id => {
<del> done("should error when create new data with non existent quality, comodity, buyer, accountBank, uom");
<add> done("should error when create new data with non existent quality, comodity, buyer, accountBank");
<ide> })
<ide> .catch(e => {
<ide> try {
<ide> e.errors.should.have.property('comodity');
<ide> e.errors.should.have.property('buyer');
<ide> e.errors.should.have.property('accountBank');
<del> e.errors.should.have.property('uom');
<ide> done();
<ide> }
<ide> catch (ex) {
|
|
Java
|
mit
|
3a4922d886e304b9b50c0292e4a646484342e01c
| 0 |
Train-Track/Train-Track-Android
|
package dyl.anjon.es.traintrack.api;
import org.w3c.dom.Element;
import dyl.anjon.es.traintrack.models.Station;
import dyl.anjon.es.traintrack.models.Operator;
import dyl.anjon.es.traintrack.utils.Utils;
public class ServiceItem {
private static final String ON_TIME = "On Time";
private Station origin;
private Station destination;
private String scheduledTimeArrival;
private String estimatedTimeArrival;
private String scheduledTimeDeparture;
private String estimatedTimeDeparture;
private String platform;
private Operator operator;
private String operatorCode;
private boolean isCircularRoute;
private String serviceId;
public ServiceItem(Element ts) {
if (ts.getElementsByTagName("origin").getLength() > 0) {
Element orig = (Element) ts.getElementsByTagName("origin").item(0);
if (orig.getElementsByTagName("crs").getLength() > 0) {
String crs = orig.getElementsByTagName("crs").item(0)
.getTextContent();
Station origin = Station.getByCrs(crs);
if (origin != null) {
this.origin = origin;
} else {
Utils.log("NO ORIGIN FOUND IN DB!");
}
}
}
if (ts.getElementsByTagName("destination").getLength() > 0) {
Element dest = (Element) ts.getElementsByTagName("destination")
.item(0);
if (dest.getElementsByTagName("crs").getLength() > 0) {
String crs = dest.getElementsByTagName("crs").item(0)
.getTextContent();
Station destination = Station.getByCrs(crs);
if (destination != null) {
this.destination = destination;
} else {
Utils.log("NO DESTINATION FOUND IN DB!");
}
}
}
if (ts.getElementsByTagName("sta").getLength() > 0) {
this.scheduledTimeArrival = ts.getElementsByTagName("sta").item(0)
.getTextContent();
}
if (ts.getElementsByTagName("eta").getLength() > 0) {
this.estimatedTimeArrival = ts.getElementsByTagName("eta").item(0)
.getTextContent();
}
if (ts.getElementsByTagName("std").getLength() > 0) {
this.scheduledTimeDeparture = ts.getElementsByTagName("std")
.item(0).getTextContent();
}
if (ts.getElementsByTagName("etd").getLength() > 0) {
this.estimatedTimeDeparture = ts.getElementsByTagName("etd")
.item(0).getTextContent();
}
if (ts.getElementsByTagName("platform").getLength() > 0) {
this.platform = ts.getElementsByTagName("platform").item(0)
.getTextContent();
}
if (ts.getElementsByTagName("operatorCode").getLength() > 0) {
this.operatorCode = ts.getElementsByTagName("operatorCode").item(0)
.getTextContent();
Operator operator = Operator.getByCode(this.operatorCode);
if (operator != null) {
this.operator = operator;
} else {
Utils.log("NO OPERATOR FOUND IN DB!");
}
}
if (ts.getElementsByTagName("isCircularRoute").getLength() > 0) {
this.isCircularRoute = Boolean.valueOf(ts
.getElementsByTagName("isCircularRoute").item(0)
.getTextContent());
}
if (ts.getElementsByTagName("serviceID").getLength() > 0) {
this.serviceId = ts.getElementsByTagName("serviceID").item(0)
.getTextContent();
}
}
public Station getOrigin() {
return origin;
}
public void setOrigin(Station origin) {
this.origin = origin;
}
public Station getDestination() {
return destination;
}
public void setDestination(Station destination) {
this.destination = destination;
}
public String getScheduledTimeArrival() {
return scheduledTimeArrival;
}
public void setScheduledTimeArrival(String scheduledTimeArrival) {
this.scheduledTimeArrival = scheduledTimeArrival;
}
public String getEstimatedTimeArrival() {
return estimatedTimeArrival;
}
public void setEstimatedTimeArrival(String estimatedTimeArrival) {
this.estimatedTimeArrival = estimatedTimeArrival;
}
public String getScheduledTimeDeparture() {
return scheduledTimeDeparture;
}
public void setScheduledTimeDeparture(String scheduledTimeDeparture) {
this.scheduledTimeDeparture = scheduledTimeDeparture;
}
public String getEstimatedTimeDeparture() {
return estimatedTimeDeparture;
}
public void setEstimatedTimeDeparture(String estimatedTimeDeparture) {
this.estimatedTimeDeparture = estimatedTimeDeparture;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
public String getOperatorCode() {
return operatorCode;
}
public void setOperatorCode(String operatorCode) {
this.operatorCode = operatorCode;
}
public boolean isCircularRoute() {
return isCircularRoute;
}
public void setCircularRoute(boolean isCircularRoute) {
this.isCircularRoute = isCircularRoute;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public boolean isDelayedDeparting() {
if (getEstimatedTimeDeparture().equalsIgnoreCase(ON_TIME)) {
return false;
} else {
return true;
}
}
public boolean isDelayedArriving() {
if (getEstimatedTimeArrival().equalsIgnoreCase(ON_TIME)) {
return false;
} else {
return true;
}
}
public boolean terminatesHere() {
if (getScheduledTimeDeparture() == null) {
return true;
} else {
return false;
}
}
public boolean startsHere() {
if (getScheduledTimeArrival() == null) {
return true;
} else {
return false;
}
}
public String toString() {
return this.getScheduledTimeDeparture() + " " + this.getOperator()
+ " service from " + this.getOrigin() + " to "
+ this.getDestination() + " on platform " + this.getPlatform();
}
}
|
src/dyl/anjon/es/traintrack/api/ServiceItem.java
|
package dyl.anjon.es.traintrack.api;
import org.w3c.dom.Element;
import dyl.anjon.es.traintrack.models.Station;
import dyl.anjon.es.traintrack.models.Operator;
import dyl.anjon.es.traintrack.utils.Utils;
public class ServiceItem {
private Station origin;
private Station destination;
private String scheduledTimeArrival;
private String estimatedTimeArrival;
private String scheduledTimeDeparture;
private String estimatedTimeDeparture;
private String platform;
private Operator operator;
private String operatorCode;
private boolean isCircularRoute;
private String serviceId;
public ServiceItem(Element ts) {
if (ts.getElementsByTagName("origin").getLength() > 0) {
Element orig = (Element) ts.getElementsByTagName("origin").item(0);
if (orig.getElementsByTagName("crs").getLength() > 0) {
String crs = orig.getElementsByTagName("crs").item(0)
.getTextContent();
Station origin = Station.getByCrs(crs);
if (origin != null) {
this.origin = origin;
} else {
Utils.log("NO ORIGIN FOUND IN DB!");
}
}
}
if (ts.getElementsByTagName("destination").getLength() > 0) {
Element dest = (Element) ts.getElementsByTagName("destination").item(0);
if (dest.getElementsByTagName("crs").getLength() > 0) {
String crs = dest.getElementsByTagName("crs").item(0)
.getTextContent();
Station destination = Station.getByCrs(crs);
if (destination != null) {
this.destination = destination;
} else {
Utils.log("NO DESTINATION FOUND IN DB!");
}
}
}
if (ts.getElementsByTagName("sta").getLength() > 0) {
this.scheduledTimeArrival = ts.getElementsByTagName("sta").item(0)
.getTextContent();
}
if (ts.getElementsByTagName("eta").getLength() > 0) {
this.estimatedTimeArrival = ts.getElementsByTagName("eta").item(0)
.getTextContent();
}
if (ts.getElementsByTagName("std").getLength() > 0) {
this.scheduledTimeDeparture = ts.getElementsByTagName("std")
.item(0).getTextContent();
}
if (ts.getElementsByTagName("etd").getLength() > 0) {
this.estimatedTimeDeparture = ts.getElementsByTagName("etd")
.item(0).getTextContent();
}
if (ts.getElementsByTagName("platform").getLength() > 0) {
this.platform = ts.getElementsByTagName("platform").item(0)
.getTextContent();
}
if (ts.getElementsByTagName("operatorCode").getLength() > 0) {
this.operatorCode = ts.getElementsByTagName("operatorCode").item(0)
.getTextContent();
Operator operator = Operator.getByCode(this.operatorCode);
if (operator != null) {
this.operator = operator;
} else {
Utils.log("NO OPERATOR FOUND IN DB!");
}
}
if (ts.getElementsByTagName("isCircularRoute").getLength() > 0) {
this.isCircularRoute = Boolean.valueOf(ts.getElementsByTagName("isCircularRoute").item(0)
.getTextContent());
}
if (ts.getElementsByTagName("serviceID").getLength() > 0) {
this.serviceId = ts.getElementsByTagName("serviceID").item(0)
.getTextContent();
}
}
public Station getOrigin() {
return origin;
}
public void setOrigin(Station origin) {
this.origin = origin;
}
public Station getDestination() {
return destination;
}
public void setDestination(Station destination) {
this.destination = destination;
}
public String getScheduledTimeArrival() {
return scheduledTimeArrival;
}
public void setScheduledTimeArrival(String scheduledTimeArrival) {
this.scheduledTimeArrival = scheduledTimeArrival;
}
public String getEstimatedTimeArrival() {
return estimatedTimeArrival;
}
public void setEstimatedTimeArrival(String estimatedTimeArrival) {
this.estimatedTimeArrival = estimatedTimeArrival;
}
public String getScheduledTimeDeparture() {
return scheduledTimeDeparture;
}
public void setScheduledTimeDeparture(String scheduledTimeDeparture) {
this.scheduledTimeDeparture = scheduledTimeDeparture;
}
public String getEstimatedTimeDeparture() {
return estimatedTimeDeparture;
}
public void setEstimatedTimeDeparture(String estimatedTimeDeparture) {
this.estimatedTimeDeparture = estimatedTimeDeparture;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
public String getOperatorCode() {
return operatorCode;
}
public void setOperatorCode(String operatorCode) {
this.operatorCode = operatorCode;
}
public boolean isCircularRoute() {
return isCircularRoute;
}
public void setCircularRoute(boolean isCircularRoute) {
this.isCircularRoute = isCircularRoute;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String toString() {
return this.getScheduledTimeDeparture() + " " + this.getOperator()
+ " service from " + this.getOrigin() + " to "
+ this.getDestination() + " on platform " + this.getPlatform();
}
}
|
adds delay helper methods
|
src/dyl/anjon/es/traintrack/api/ServiceItem.java
|
adds delay helper methods
|
<ide><path>rc/dyl/anjon/es/traintrack/api/ServiceItem.java
<ide>
<ide> public class ServiceItem {
<ide>
<add> private static final String ON_TIME = "On Time";
<ide> private Station origin;
<ide> private Station destination;
<ide> private String scheduledTimeArrival;
<ide> }
<ide> }
<ide> if (ts.getElementsByTagName("destination").getLength() > 0) {
<del> Element dest = (Element) ts.getElementsByTagName("destination").item(0);
<add> Element dest = (Element) ts.getElementsByTagName("destination")
<add> .item(0);
<ide> if (dest.getElementsByTagName("crs").getLength() > 0) {
<ide> String crs = dest.getElementsByTagName("crs").item(0)
<ide> .getTextContent();
<ide> }
<ide> }
<ide> if (ts.getElementsByTagName("isCircularRoute").getLength() > 0) {
<del> this.isCircularRoute = Boolean.valueOf(ts.getElementsByTagName("isCircularRoute").item(0)
<add> this.isCircularRoute = Boolean.valueOf(ts
<add> .getElementsByTagName("isCircularRoute").item(0)
<ide> .getTextContent());
<ide> }
<ide> if (ts.getElementsByTagName("serviceID").getLength() > 0) {
<ide>
<ide> public void setServiceId(String serviceId) {
<ide> this.serviceId = serviceId;
<add> }
<add>
<add> public boolean isDelayedDeparting() {
<add> if (getEstimatedTimeDeparture().equalsIgnoreCase(ON_TIME)) {
<add> return false;
<add> } else {
<add> return true;
<add> }
<add> }
<add>
<add> public boolean isDelayedArriving() {
<add> if (getEstimatedTimeArrival().equalsIgnoreCase(ON_TIME)) {
<add> return false;
<add> } else {
<add> return true;
<add> }
<add> }
<add>
<add> public boolean terminatesHere() {
<add> if (getScheduledTimeDeparture() == null) {
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> }
<add>
<add> public boolean startsHere() {
<add> if (getScheduledTimeArrival() == null) {
<add> return true;
<add> } else {
<add> return false;
<add> }
<ide> }
<ide>
<ide> public String toString() {
|
|
Java
|
apache-2.0
|
14d0bcd589dd88bbe5a177a0b06863a71418bd6b
| 0 |
scorpionvicky/elasticsearch,nknize/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,strapdata/elassandra,gingerwizard/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,gfyoung/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,vroyer/elassandra,HonzaKral/elasticsearch,nknize/elasticsearch,gfyoung/elasticsearch,coding0011/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch,scorpionvicky/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,HonzaKral/elasticsearch,coding0011/elasticsearch,HonzaKral/elasticsearch,gfyoung/elasticsearch,strapdata/elassandra,GlenRSmith/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,scorpionvicky/elasticsearch,gingerwizard/elasticsearch,vroyer/elassandra,gingerwizard/elasticsearch,HonzaKral/elasticsearch,uschindler/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch,scorpionvicky/elasticsearch,strapdata/elassandra,GlenRSmith/elasticsearch,uschindler/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,scorpionvicky/elasticsearch,gfyoung/elasticsearch,vroyer/elassandra,gingerwizard/elasticsearch,nknize/elasticsearch,robin13/elasticsearch,strapdata/elassandra
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.alerting;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.DateTime;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.*;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.simpl.SimpleJobFactory;
import java.io.IOException;
import java.util.Date;
public class AlertScheduler extends AbstractLifecycleComponent {
Scheduler scheduler = null;
private final AlertManager alertManager;
private final Client client;
private final TriggerManager triggerManager;
private final AlertActionManager actionManager;
@Inject
public AlertScheduler(Settings settings, AlertManager alertManager, Client client,
TriggerManager triggerManager, AlertActionManager actionManager) {
super(settings);
this.alertManager = alertManager;
this.client = client;
this.triggerManager = triggerManager;
this.actionManager = actionManager;
try {
SchedulerFactory schFactory = new StdSchedulerFactory();
scheduler = schFactory.getScheduler();
scheduler.setJobFactory(new SimpleJobFactory());
} catch (Throwable t) {
logger.error("Failed to instantiate scheduler", t);
}
}
public boolean deleteAlertFromSchedule(String alertName) {
try {
scheduler.deleteJob(new JobKey(alertName));
return true;
} catch (SchedulerException se){
throw new ElasticsearchException("Failed to remove [" + alertName + "] from the scheduler", se);
}
}
public void clearAlerts() {
try {
scheduler.clear();
} catch (SchedulerException se){
throw new ElasticsearchException("Failed to clear scheduler", se);
}
}
public void executeAlert(String alertName, JobExecutionContext jobExecutionContext){
logger.warn("Running [{}]",alertName);
Alert alert = alertManager.getAlertForName(alertName);
DateTime scheduledTime = new DateTime(jobExecutionContext.getScheduledFireTime());
if (!alert.enabled()) {
logger.warn("Alert [{}] is not enabled", alertName);
return;
}
try {
if (!alertManager.claimAlertRun(alertName, scheduledTime) ){
logger.warn("Another process has already run this alert.");
return;
}
XContentBuilder builder = createClampedQuery(jobExecutionContext, alert);
logger.warn("Running the following query : [{}]", builder.string());
SearchRequestBuilder srb = client.prepareSearch().setSource(builder);
String[] indices = alert.indices().toArray(new String[0]);
if (alert.indices() != null ){
logger.warn("Setting indices to : " + alert.indices());
srb.setIndices(indices);
}
SearchResponse sr = srb.execute().get();
logger.warn("Got search response hits : [{}]", sr.getHits().getTotalHits() );
AlertResult result = new AlertResult(alertName, sr, alert.trigger(),
triggerManager.isTriggered(alertName,sr), builder, indices,
new DateTime(jobExecutionContext.getScheduledFireTime()));
if (result.isTriggered) {
logger.warn("We have triggered");
actionManager.doAction(alertName,result);
logger.warn("Did action !");
}else{
logger.warn("We didn't trigger");
}
alertManager.updateLastRan(alertName, new DateTime(jobExecutionContext.getFireTime()));
if (!alertManager.addHistory(alertName, result.isTriggered,
new DateTime(jobExecutionContext.getScheduledFireTime()), result.query,
result.trigger, result.searchResponse.getHits().getTotalHits(), alert.indices()))
{
logger.warn("Failed to store history for alert [{}]", alertName);
}
} catch (Exception e) {
logger.error("Failed execute alert [{}]", e, alertName);
}
}
private XContentBuilder createClampedQuery(JobExecutionContext jobExecutionContext, Alert alert) throws IOException {
Date scheduledFireTime = jobExecutionContext.getScheduledFireTime();
DateTime clampEnd = new DateTime(scheduledFireTime);
DateTime clampStart = clampEnd.minusSeconds((int)alert.timePeriod().seconds());
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.startObject();
builder.field("query");
builder.startObject();
builder.field("filtered");
builder.startObject();
builder.field("query");
builder.startObject();
builder.field("template");
builder.startObject();
builder.field("id");
builder.value(alert.queryName());
builder.endObject();
builder.endObject();
builder.field("filter");
builder.startObject();
builder.field("range");
builder.startObject();
builder.field("@timestamp");
builder.startObject();
builder.field("gte");
builder.value(clampStart);
builder.field("lt");
builder.value(clampEnd);
builder.endObject();
builder.endObject();
builder.endObject();
builder.endObject();
builder.endObject();
return builder;
}
public void addAlert(String alertName, Alert alert) {
JobDetail job = JobBuilder.newJob(org.elasticsearch.alerting.AlertExecutorJob.class).withIdentity(alertName).build();
job.getJobDataMap().put("manager",this);
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(alert.schedule()))
.build();
try {
logger.warn("Scheduling [{}] with schedule [{}]", alertName, alert.schedule());
scheduler.scheduleJob(job, cronTrigger);
} catch (SchedulerException se) {
logger.error("Failed to schedule job",se);
}
}
@Override
protected void doStart() throws ElasticsearchException {
logger.warn("Starting Scheduler");
try {
scheduler.start();
} catch (SchedulerException se){
logger.error("Failed to start quartz scheduler",se);
}
}
@Override
protected void doStop() throws ElasticsearchException {
try {
scheduler.shutdown(true);
} catch (SchedulerException se){
logger.error("Failed to stop quartz scheduler",se);
}
}
@Override
protected void doClose() throws ElasticsearchException {
}
}
|
src/main/java/org/elasticsearch/alerting/AlertScheduler.java
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.alerting;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.DateTime;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.*;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.simpl.SimpleJobFactory;
import java.io.IOException;
import java.util.Date;
public class AlertScheduler extends AbstractLifecycleComponent {
Scheduler scheduler = null;
private final AlertManager alertManager;
private final Client client;
private final TriggerManager triggerManager;
private final AlertActionManager actionManager;
@Inject
public AlertScheduler(Settings settings, AlertManager alertManager, Client client,
TriggerManager triggerManager, AlertActionManager actionManager) {
super(settings);
this.alertManager = alertManager;
this.client = client;
this.triggerManager = triggerManager;
this.actionManager = actionManager;
try {
SchedulerFactory schFactory = new StdSchedulerFactory();
scheduler = schFactory.getScheduler();
scheduler.setJobFactory(new SimpleJobFactory());
} catch (Throwable t) {
logger.error("Failed to instantiate scheduler", t);
}
}
public boolean deleteAlertFromSchedule(String alertName) {
try {
scheduler.deleteJob(new JobKey(alertName));
return true;
} catch (SchedulerException se){
throw new ElasticsearchException("Failed to remove [" + alertName + "] from the scheduler", se);
}
}
public void clearAlerts() {
try {
scheduler.clear();
} catch (SchedulerException se){
throw new ElasticsearchException("Failed to clear scheduler", se);
}
}
public void executeAlert(String alertName, JobExecutionContext jobExecutionContext){
logger.warn("Running [{}]",alertName);
Alert alert = alertManager.getAlertForName(alertName);
DateTime scheduledTime = new DateTime(jobExecutionContext.getScheduledFireTime());
if (!alert.enabled()) {
logger.warn("Alert [{}] is not enabled", alertName);
}
try {
if (!alertManager.claimAlertRun(alertName, scheduledTime) ){
logger.warn("Another process has already run this alert.");
return;
}
XContentBuilder builder = createClampedQuery(jobExecutionContext, alert);
logger.warn("Running the following query : [{}]", builder.string());
SearchRequestBuilder srb = client.prepareSearch().setSource(builder);
String[] indices = alert.indices().toArray(new String[0]);
if (alert.indices() != null ){
logger.warn("Setting indices to : " + alert.indices());
srb.setIndices(indices);
}
SearchResponse sr = srb.execute().get();
logger.warn("Got search response hits : [{}]", sr.getHits().getTotalHits() );
AlertResult result = new AlertResult(alertName, sr, alert.trigger(),
triggerManager.isTriggered(alertName,sr), builder, indices,
new DateTime(jobExecutionContext.getScheduledFireTime()));
if (result.isTriggered) {
logger.warn("We have triggered");
actionManager.doAction(alertName,result);
logger.warn("Did action !");
}else{
logger.warn("We didn't trigger");
}
alertManager.updateLastRan(alertName, new DateTime(jobExecutionContext.getFireTime()));
if (!alertManager.addHistory(alertName, result.isTriggered,
new DateTime(jobExecutionContext.getScheduledFireTime()), result.query,
result.trigger, result.searchResponse.getHits().getTotalHits(), alert.indices()))
{
logger.warn("Failed to store history for alert [{}]", alertName);
}
} catch (Exception e) {
logger.error("Failed execute alert [{}]", e, alertName);
}
}
private XContentBuilder createClampedQuery(JobExecutionContext jobExecutionContext, Alert alert) throws IOException {
Date scheduledFireTime = jobExecutionContext.getScheduledFireTime();
DateTime clampEnd = new DateTime(scheduledFireTime);
DateTime clampStart = clampEnd.minusSeconds((int)alert.timePeriod().seconds());
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.startObject();
builder.field("query");
builder.startObject();
builder.field("filtered");
builder.startObject();
builder.field("query");
builder.startObject();
builder.field("template");
builder.startObject();
builder.field("id");
builder.value(alert.queryName());
builder.endObject();
builder.endObject();
builder.field("filter");
builder.startObject();
builder.field("range");
builder.startObject();
builder.field("@timestamp");
builder.startObject();
builder.field("gte");
builder.value(clampStart);
builder.field("lt");
builder.value(clampEnd);
builder.endObject();
builder.endObject();
builder.endObject();
builder.endObject();
builder.endObject();
return builder;
}
public void addAlert(String alertName, Alert alert) {
JobDetail job = JobBuilder.newJob(org.elasticsearch.alerting.AlertExecutorJob.class).withIdentity(alertName).build();
job.getJobDataMap().put("manager",this);
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(alert.schedule()))
.build();
try {
logger.warn("Scheduling [{}] with schedule [{}]", alertName, alert.schedule());
scheduler.scheduleJob(job, cronTrigger);
} catch (SchedulerException se) {
logger.error("Failed to schedule job",se);
}
}
@Override
protected void doStart() throws ElasticsearchException {
logger.warn("Starting Scheduler");
try {
scheduler.start();
} catch (SchedulerException se){
logger.error("Failed to start quartz scheduler",se);
}
}
@Override
protected void doStop() throws ElasticsearchException {
try {
scheduler.shutdown(true);
} catch (SchedulerException se){
logger.error("Failed to stop quartz scheduler",se);
}
}
@Override
protected void doClose() throws ElasticsearchException {
}
}
|
Alerting add TODO
Original commit: elastic/x-pack-elasticsearch@23cf5fce8bd27049ce45f2bbce8f9ddd6b9ae77b
|
src/main/java/org/elasticsearch/alerting/AlertScheduler.java
|
Alerting add TODO
|
<ide><path>rc/main/java/org/elasticsearch/alerting/AlertScheduler.java
<ide> DateTime scheduledTime = new DateTime(jobExecutionContext.getScheduledFireTime());
<ide> if (!alert.enabled()) {
<ide> logger.warn("Alert [{}] is not enabled", alertName);
<add> return;
<ide> }
<ide> try {
<ide> if (!alertManager.claimAlertRun(alertName, scheduledTime) ){
|
|
Java
|
bsd-3-clause
|
b6d63f93196e5bc80e3e345287d21c4d8ebee5c6
| 0 |
appcelerator/jaxen_titanium,ukcrpb6/jaxen-wmb-extensions
|
package org.jaxen;
/*
$Id$
Copyright 2003 (C) The Werken Company. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "jaxen" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Werken Company. For written permission,
please contact [email protected].
4. Products derived from this Software may not be called "jaxen"
nor may "jaxen" appear in their names without prior written
permission of The Werken Company. "jaxen" is a registered
trademark of The Werken Company.
5. Due credit should be given to The Werken Company.
(http://jaxen.werken.com/).
THIS SOFTWARE IS PROVIDED BY THE WERKEN COMPANY AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE WERKEN COMPANY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.Serializable;
/** Supporting context information for resolving
* namespace prefixes, functions, and variables.
*
* <p>
* <b>NOTE:</b> This class is not typically used directly,
* but is exposed for writers of implementation-specific
* XPath packages.
* </p>
*
* @see org.jaxen.dom4j.Dom4jXPath XPath for dom4j
* @see org.jaxen.jdom.JDOMXPath XPath for JDOM
* @see org.jaxen.dom.DOMXPath XPath for W3C DOM
*
* @author <a href="mailto:[email protected]">bob mcwhirter</a>
*
* @version $Id$
*/
public class ContextSupport
implements Serializable
{
/** Function context. */
private transient FunctionContext functionContext;
/** Namespace context. */
private NamespaceContext namespaceContext;
/** Variable context. */
private VariableContext variableContext;
/** Model navigator. */
private Navigator navigator;
// ----------------------------------------------------------------------
// Constructors
// ----------------------------------------------------------------------
/** Construct an empty <code>ContextSupport</code>.
*/
public ContextSupport()
{
// intentionally left blank
}
/** Construct.
*
* @param namespaceContext the NamespaceContext
* @param functionContext the FunctionContext
* @param variableContext the VariableContext
* @param navigator the model navigator
*/
public ContextSupport(NamespaceContext namespaceContext,
FunctionContext functionContext,
VariableContext variableContext,
Navigator navigator)
{
setNamespaceContext( namespaceContext );
setFunctionContext( functionContext );
setVariableContext( variableContext );
this.navigator = navigator;
}
// ----------------------------------------------------------------------
// Instance methods
// ----------------------------------------------------------------------
/** Set the <code>NamespaceContext</code>.
*
* @param namespaceContext the namespace context
*/
public void setNamespaceContext(NamespaceContext namespaceContext)
{
this.namespaceContext = namespaceContext;
}
/** Retrieve the <code>NamespaceContext</code>.
*
* @return the namespace context
*/
public NamespaceContext getNamespaceContext()
{
return this.namespaceContext;
}
/** Set the <code>FunctionContext</code>.
*
* @param functionContext the function context
*/
public void setFunctionContext(FunctionContext functionContext)
{
this.functionContext = functionContext;
}
/** Retrieve the <code>FunctionContext</code>.
*
* @return the function context
*/
public FunctionContext getFunctionContext()
{
return this.functionContext;
}
/** Set the <code>VariableContext</code>.
*
* @param variableContext the variable context
*/
public void setVariableContext(VariableContext variableContext)
{
this.variableContext = variableContext;
}
/** Retrieve the <code>VariableContext</code>.
*
* @return the variable context
*/
public VariableContext getVariableContext()
{
return this.variableContext;
}
/** Retrieve the <code>Navigator</code>.
*
* @return the navigator
*/
public Navigator getNavigator()
{
return this.navigator;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/** Translate a namespace prefix to its URI.
*
* @param prefix The prefix
*
* @return the namespace URI mapped to the prefix
*/
public String translateNamespacePrefixToUri(String prefix)
{
if ("xml".equals(prefix)) {
return "http://www.w3.org/XML/1998/namespace";
}
NamespaceContext context = getNamespaceContext();
if ( context != null )
{
return context.translateNamespacePrefixToUri( prefix );
}
return null;
}
/** Retrieve a variable value.
*
* @param namespaceURI the function namespace URI
* @param prefix the function prefix
* @param localName the function name
*
* @return the variable value.
*
* @throws UnresolvableException if unable to locate a bound variable.
*/
public Object getVariableValue( String namespaceURI,
String prefix,
String localName )
throws UnresolvableException
{
VariableContext context = getVariableContext();
if ( context != null )
{
return context.getVariableValue( namespaceURI, prefix, localName );
}
else
{
throw new UnresolvableException( "No variable context installed" );
}
}
/** Retrieve a <code>Function</code>.
*
* @param namespaceURI the function namespace URI
* @param prefix the function prefix
* @param localName the function name
*
* @return the function object
*
* @throws UnresolvableException if unable to locate a bound function
*/
public Function getFunction( String namespaceURI,
String prefix,
String localName )
throws UnresolvableException
{
FunctionContext context = getFunctionContext();
if ( context != null )
{
return context.getFunction( namespaceURI, prefix, localName );
}
else
{
throw new UnresolvableException( "No function context installed" );
}
}
}
|
src/java/main/org/jaxen/ContextSupport.java
|
package org.jaxen;
/*
$Id$
Copyright 2003 (C) The Werken Company. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "jaxen" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Werken Company. For written permission,
please contact [email protected].
4. Products derived from this Software may not be called "jaxen"
nor may "jaxen" appear in their names without prior written
permission of The Werken Company. "jaxen" is a registered
trademark of The Werken Company.
5. Due credit should be given to The Werken Company.
(http://jaxen.werken.com/).
THIS SOFTWARE IS PROVIDED BY THE WERKEN COMPANY AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE WERKEN COMPANY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.Serializable;
/** Supporting context information for resolving
* namespace prefixes, functions, and variables.
*
* <p>
* <b>NOTE:</b> This class is not typically used directly,
* but is exposed for writers of implementation-specific
* XPath packages.
* </p>
*
* @see org.jaxen.dom4j.Dom4jXPath XPath for dom4j
* @see org.jaxen.jdom.JDOMXPath XPath for JDOM
* @see org.jaxen.dom.DOMXPath XPath for W3C DOM
*
* @author <a href="mailto:[email protected]">bob mcwhirter</a>
*
* @version $Id$
*/
public class ContextSupport
implements Serializable
{
// ----------------------------------------------------------------------
// Instance methods
// ----------------------------------------------------------------------
/** Function context. */
private transient FunctionContext functionContext;
/** Namespace context. */
private NamespaceContext namespaceContext;
/** Variable context. */
private VariableContext variableContext;
/** Model navigator. */
private Navigator navigator;
// ----------------------------------------------------------------------
// Constructors
// ----------------------------------------------------------------------
/** Construct an empty <code>ContextSupport</code>.
*/
public ContextSupport()
{
// intentionally left blank
}
/** Construct.
*
* @param namespaceContext the NamespaceContext
* @param functionContext the FunctionContext
* @param variableContext the VariableContext
* @param navigator the model navigator
*/
public ContextSupport(NamespaceContext namespaceContext,
FunctionContext functionContext,
VariableContext variableContext,
Navigator navigator)
{
setNamespaceContext( namespaceContext );
setFunctionContext( functionContext );
setVariableContext( variableContext );
this.navigator = navigator;
}
// ----------------------------------------------------------------------
// Instance methods
// ----------------------------------------------------------------------
/** Set the <code>NamespaceContext</code>.
*
* @param namespaceContext the namespace context
*/
public void setNamespaceContext(NamespaceContext namespaceContext)
{
this.namespaceContext = namespaceContext;
}
/** Retrieve the <code>NamespaceContext</code>.
*
* @return the namespace context
*/
public NamespaceContext getNamespaceContext()
{
return this.namespaceContext;
}
/** Set the <code>FunctionContext</code>.
*
* @param functionContext the function context
*/
public void setFunctionContext(FunctionContext functionContext)
{
this.functionContext = functionContext;
}
/** Retrieve the <code>FunctionContext</code>.
*
* @return the function context
*/
public FunctionContext getFunctionContext()
{
return this.functionContext;
}
/** Set the <code>VariableContext</code>.
*
* @param variableContext the variable context
*/
public void setVariableContext(VariableContext variableContext)
{
this.variableContext = variableContext;
}
/** Retrieve the <code>VariableContext</code>.
*
* @return the variable context
*/
public VariableContext getVariableContext()
{
return this.variableContext;
}
/** Retrieve the <code>Navigator</code>.
*
* @return the navigator
*/
public Navigator getNavigator()
{
return this.navigator;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/** Translate a namespace prefix to its URI.
*
* @param prefix The prefix
*
* @return the namespace URI mapped to the prefix
*/
public String translateNamespacePrefixToUri(String prefix)
{
if ("xml".equals(prefix)) {
return "http://www.w3.org/XML/1998/namespace";
}
NamespaceContext context = getNamespaceContext();
if ( context != null )
{
return context.translateNamespacePrefixToUri( prefix );
}
return null;
}
/** Retrieve a variable value.
*
* @param namespaceURI the function namespace URI
* @param prefix the function prefix
* @param localName the function name
*
* @return the variable value.
*
* @throws UnresolvableException if unable to locate a bound variable.
*/
public Object getVariableValue( String namespaceURI,
String prefix,
String localName )
throws UnresolvableException
{
VariableContext context = getVariableContext();
if ( context != null )
{
return context.getVariableValue( namespaceURI, prefix, localName );
}
else
{
throw new UnresolvableException( "No variable context installed" );
}
}
/** Retrieve a <code>Function</code>.
*
* @param namespaceURI the function namespace URI
* @param prefix the function prefix
* @param localName the function name
*
* @return the function object
*
* @throws UnresolvableException if unable to locate a bound function
*/
public Function getFunction( String namespaceURI,
String prefix,
String localName )
throws UnresolvableException
{
FunctionContext context = getFunctionContext();
if ( context != null )
{
return context.getFunction( namespaceURI, prefix, localName );
}
else
{
throw new UnresolvableException( "No function context installed" );
}
}
}
|
Removing incorrect comment
git-svn-id: 7abf240ce0ec4644a9bf59262a41ad5796234f37@795 43379f7c-b030-0410-81db-e0b70742847c
|
src/java/main/org/jaxen/ContextSupport.java
|
Removing incorrect comment
|
<ide><path>rc/java/main/org/jaxen/ContextSupport.java
<ide> public class ContextSupport
<ide> implements Serializable
<ide> {
<del> // ----------------------------------------------------------------------
<del> // Instance methods
<del> // ----------------------------------------------------------------------
<ide>
<ide> /** Function context. */
<ide> private transient FunctionContext functionContext;
|
|
JavaScript
|
mit
|
d04dc7948920a6f08aba81a978b564a8e1c33974
| 0 |
Ezphares/sw809f14,Ezphares/sw809f14,Ezphares/sw809f14,Ezphares/sw809f14
|
/**
* A class representing a route planner, containing a map and tools to add and remove waypoints to a route
* @class
* @param {String} map A css selector identifying the element to contain the map
* @param {String} controls A css selector identifying the element to contain waypoint controls
* @param {String} info A css selector identifying the element to display route information
* @param {String} load A css selector identifying an element of the map to load information from. An empty map will be loaded if this element does not exist
* @param {Number[]} [mapsize] the size of the map in pixels, given as [width, height]
*/
Planner = function(map, controls, info, load, mapsize)
{
// Mapsize is optional
mapsize = mapsize || [640, 480];
/** JQuery selectors of the elements used by the planner */
this.elements = {'map': $(map), 'controls': $(controls), 'info': $(info), 'load': $(load)};
/** The google map object */
this.map = null;
/** An array of google map markers */
this.markers = [];
/** A google maps directions service instance */
this.directions = new google.maps.DirectionsService();
/** A google maps directionsrenderer instance */
this.route_renderer = null;
/** a google maps route information instance */
this.route = null;
/** Whether the route should start and end at the same point */
this.round_trip = false;
/** jQuery selector of a container where the route json is placed for upload */
this.json_container = null;
// Setup map size
this.elements.map.css({'width': mapsize[0] + 'px',
'height': mapsize[1] + 'px'});
this.elements.info.css({'height': mapsize[1] + 'px'});
this.initialize_map(this.elements.map[0]);
this.initialize_controls();
this.update_info();
};
/**
* Initializes the google map. First tests whether geolocation is available,
* and if so, centers the map on the user.
* <br />Called automatically by constructor.
* @param {Node} target The html element to contain the map
*/
Planner.prototype.initialize_map = function(target)
{
// Allow 'this' reference through callbacks
var planner = this;
var options = {'center': new google.maps.LatLng(-34.397, 150.644),
'zoom': 12};
// Callback function
var load_map = function()
{
console.log(target);
planner.map = new google.maps.Map(target, options);
planner.map_events();
if (planner.elements.load.length)
planner.load(planner.elements.load.html());
};
// Check if geolocation is supported
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(pos)
{
// Successful geolocation
options.center = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
load_map();
}, function()
{
// Failed geolocation. Permission denied?
load_map();
});
}
else
// Geolocation was not supported
load_map();
};
/**
* Sets up events for map and markers.
* <br />Called automatically by initialize_map.
*/
Planner.prototype.map_events = function()
{
// Allow 'this' reference through callbacks
var planner = this;
// Event to add a waypoint
google.maps.event.addListener(this.map, 'click', function(ev)
{
if (planner.markers.length >= 9)
return;
planner.add_marker(ev.latLng)
});
};
/**
* Updates the route display of the route planner.
* <br /> Called automatically by several events.
*/
Planner.prototype.update_route = function()
{
// Set map icons
for (var i = 0; i < this.markers.length; i++)
{
this.markers[i].setIcon(STATIC_URL + 'img/number_' + (i + 1) + '.png');
this.markers[i].setMap(this.map);
}
// Allow 'this' reference through callbacks
var planner = this;
if (this.markers.length >= 2)
{
var plan = []
// Extract positions. This has the nice side effect of copying the array, so markers are unaffected later on.
for (var i = 0; i < this.markers.length; i++)
{
plan.push(this.markers[i].getPosition());
}
// If we are round-tripping, end at the last waypoint
if (this.round_trip)
plan.push(plan[0]);
// Extract start and end point
var destination = plan.reverse().shift();
var origin = plan.reverse().shift();
// Plan now contains intermediate waypoints. Wrap these so google maps understands them
for (var i = 0; i < plan.length; i++)
{
// Using stopover true, because it changes route algorithm to allow turning around on the spot
plan[i] = {'location': plan[i], 'stopover': true};
}
var route_options = {'origin': origin,
'destination': destination,
'waypoints': plan,
'travelMode': google.maps.TravelMode.WALKING,
'avoidHighways': true,
'avoidTolls': true,
'optimizeWaypoints': false};
this.directions.route(route_options, function(result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
planner.route = result.routes[0];
// Update existing route if possible, otherwise create a new route
if (planner.route_renderer)
{
planner.route_renderer.setDirections(result);
}
else
{
var direction_options = {'directions': result,
'draggable': false, // We use custom draggable markers instead
'map': planner.map,
'suppressMarkers': true,
'preserveViewport': true}
planner.route_renderer = new google.maps.DirectionsRenderer(direction_options);
}
planner.update_info();
}
else
{
// Creating the route somehow failed
// TODO: Handle nicely
alert('Directions request failed: ' + status);
}
});
}
else
{
// Remove previous route
if (this.route_renderer)
{
this.route_renderer.setMap();
this.route_renderer = null;
}
this.update_info();
}
};
/**
* Initializes the planner controls
* <br >Called automatically by constructor
*/
Planner.prototype.initialize_controls = function()
{
// Allow 'this' reference through callbacks
var planner = this;
$('<button>Clear</button>').appendTo(this.elements.controls).click(function(ev)
{
planner.clear();
});
$('<button>Reverse</button>').appendTo(this.elements.controls).click(function(ev)
{
planner.markers.reverse();
planner.update_route();
});
$('<label>Round-trip?<input type="checkbox"/></label>').appendTo(this.elements.controls).find('input').change(function(ev)
{
planner.round_trip = $(this).is(':checked');
planner.update_route();
});
this.json_container = $('<input type="hidden" name="json" />');
$('<form action="" method="POST"><input type="text" name="name" value="Route name" /><input type="submit" /></form>').append(this.json_container).append(CSRF).appendTo(this.elements.controls);
};
/**
* Clears route and markers from the map
*/
Planner.prototype.clear = function()
{
// Clear all markers, avoiding leaks
for (var i = 0; i < this.markers.length; i++)
{
this.markers[i].setMap();
}
this.markers = [];
// Clear route
if (this.route_renderer)
this.route_renderer.setMap();
this.route_renderer = null;
this.update_info();
};
/**
* Updates the route information view
*/
Planner.prototype.update_info = function()
{
this.elements.info.html('');
if (!this.route_renderer)
{
$('<span></span>').text("No route entered").appendTo(this.elements.info);
this.json_container.val('{"waypoints":[]}');
}
else
{
var distance = 0;
for (var i = 0; i < this.route.legs.length; i++)
{
distance += this.route.legs[i].distance.value;
}
$('<span></span>').text("Route distance: " + distance + 'm').appendTo(this.elements.info);
var waypoints = [];
for (var i = 0; i < this.markers.length; i++)
{
waypoints.push({'lat': this.markers[i].getPosition().lat(), 'lng': this.markers[i].getPosition().lng()});
}
this.json_container.val(JSON.stringify({'waypoints': waypoints,
'distance': distance})); // TODO: Enter score here
}
}
/**
* Loads a route from a json representation
* @param {JSON} json the json representation to load
*/
Planner.prototype.load = function(json)
{
// TODO: Validate json
var data = JSON.parse(json);
console.log(data);
this.elements.controls.find('input[name="name"]').val(data['name']);
for (var i = 0; i < data.waypoints.length; i++)
this.add_marker(new google.maps.LatLng(data.waypoints[i].lat, data.waypoints[i].lng))
console.log(this.markers);
this.update_route();
}
/*
* Adds a marker to the map, adding relevant events and updates the directions
* @param {google.maps.LatLng} position The LatLng object representing the position to add the marker
*/
Planner.prototype.add_marker = function(position)
{
// Allow 'this' reference through callbacks
var planner = this;
var marker_options = {'position': position,
'draggable': true};
var marker = new google.maps.Marker(marker_options);
this.markers.push(marker);
this.update_route(planner);
// Event to remove said waypoint
google.maps.event.addListener(marker, 'rightclick', function(ev)
{
marker.setMap();
var index = planner.markers.indexOf(marker);
if (index >= 0)
planner.markers.splice(index, 1);
planner.update_route(planner);
});
// Event on drag
google.maps.event.addListener(marker, 'dragend', function(ev)
{
planner.update_route(planner);
});
};
|
runweb/static/js/planner.js
|
/**
* A class representing a route planner, containing a map and tools to add and remove waypoints to a route
* @class
* @param {String} map A css selector identifying the element to contain the map
* @param {String} controls A css selector identifying the element to contain waypoint controls
* @param {String} info A css selector identifying the element to display route information
* @param {String} load A css selector identifying an element of the map to load information from. An empty map will be loaded if this element does not exist
* @param {Number[]} [mapsize] the size of the map in pixels, given as [width, height]
*/
Planner = function(map, controls, info, load, mapsize)
{
// Mapsize is optional
mapsize = mapsize || [640, 480];
/** JQuery selectors of the elements used by the planner */
this.elements = {'map': $(map), 'controls': $(controls), 'info': $(info), 'load': $(load)};
/** The google map object */
this.map = null;
/** An array of google map markers */
this.markers = [];
/** A google maps directions service instance */
this.directions = new google.maps.DirectionsService();
/** A google maps directionsrenderer instance */
this.route_renderer = null;
/** a google maps route information instance */
this.route = null;
/** Whether the route should start and end at the same point */
this.round_trip = false;
/** jQuery selector of a container where the route json is placed for upload */
this.json_container = null;
// Setup map size
this.elements.map.css({'width': mapsize[0] + 'px',
'height': mapsize[1] + 'px'});
this.elements.info.css({'height': mapsize[1] + 'px'});
this.initialize_map(this.elements.map[0]);
this.initialize_controls();
this.update_info();
};
/**
* Initializes the google map. First tests whether geolocation is available,
* and if so, centers the map on the user.
* <br />Called automatically by constructor.
* @param {Node} target The html element to contain the map
*/
Planner.prototype.initialize_map = function(target)
{
// Allow 'this' reference through callbacks
var planner = this;
var options = {'center': new google.maps.LatLng(-34.397, 150.644),
'zoom': 12};
// Callback function
var load_map = function()
{
console.log(target);
planner.map = new google.maps.Map(target, options);
planner.map_events();
if (planner.elements.load.length)
planner.load(planner.elements.load.html());
};
// Check if geolocation is supported
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(pos)
{
// Successful geolocation
options.center = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
load_map();
}, function()
{
// Failed geolocation. Permission denied?
load_map();
});
}
else
// Geolocation was not supported
load_map();
};
/**
* Sets up events for map and markers.
* <br />Called automatically by initialize_map.
*/
Planner.prototype.map_events = function()
{
// Allow 'this' reference through callbacks
var planner = this;
// Event to add a waypoint
google.maps.event.addListener(this.map, 'click', function(ev)
{
if (planner.markers.length >= 9)
return;
// TODO: Create marker function
var marker_options = {'position': ev.latLng,
'draggable': true};
var marker = new google.maps.Marker(marker_options);
planner.markers.push(marker);
planner.update_route(planner);
// Event to remove said waypoint
google.maps.event.addListener(marker, 'rightclick', function(ev)
{
marker.setMap();
var index = planner.markers.indexOf(marker);
if (index >= 0)
planner.markers.splice(index, 1);
planner.update_route(planner);
});
// Event on drag
google.maps.event.addListener(marker, 'dragend', function(ev)
{
planner.update_route(planner);
});
});
};
/**
* Updates the route display of the route planner.
* <br /> Called automatically by several events.
*/
Planner.prototype.update_route = function()
{
// Set map icons
for (var i = 0; i < this.markers.length; i++)
{
this.markers[i].setIcon(STATIC_URL + 'img/number_' + (i + 1) + '.png');
this.markers[i].setMap(this.map);
}
// Allow 'this' reference through callbacks
var planner = this;
if (this.markers.length >= 2)
{
var plan = []
// Extract positions. This has the nice side effect of copying the array, so markers are unaffected later on.
for (var i = 0; i < this.markers.length; i++)
{
plan.push(this.markers[i].getPosition());
}
// If we are round-tripping, end at the last waypoint
if (this.round_trip)
plan.push(plan[0]);
// Extract start and end point
var destination = plan.reverse().shift();
var origin = plan.reverse().shift();
// Plan now contains intermediate waypoints. Wrap these so google maps understands them
for (var i = 0; i < plan.length; i++)
{
// Using stopover true, because it changes route algorithm to allow turning around on the spot
plan[i] = {'location': plan[i], 'stopover': true};
}
var route_options = {'origin': origin,
'destination': destination,
'waypoints': plan,
'travelMode': google.maps.TravelMode.WALKING,
'avoidHighways': true,
'avoidTolls': true,
'optimizeWaypoints': false};
this.directions.route(route_options, function(result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
planner.route = result.routes[0];
// Update existing route if possible, otherwise create a new route
if (planner.route_renderer)
{
planner.route_renderer.setDirections(result);
}
else
{
var direction_options = {'directions': result,
'draggable': false, // We use custom draggable markers instead
'map': planner.map,
'suppressMarkers': true,
'preserveViewport': true}
planner.route_renderer = new google.maps.DirectionsRenderer(direction_options);
}
planner.update_info();
}
else
{
// Creating the route somehow failed
// TODO: Handle nicely
alert('Directions request failed: ' + status);
}
});
}
else
{
// Remove previous route
if (this.route_renderer)
{
this.route_renderer.setMap();
this.route_renderer = null;
}
this.update_info();
}
};
/**
* Initializes the planner controls
* <br >Called automatically by constructor
*/
Planner.prototype.initialize_controls = function()
{
// Allow 'this' reference through callbacks
var planner = this;
$('<button>Clear</button>').appendTo(this.elements.controls).click(function(ev)
{
planner.clear();
});
$('<button>Reverse</button>').appendTo(this.elements.controls).click(function(ev)
{
planner.markers.reverse();
planner.update_route();
});
$('<label>Round-trip?<input type="checkbox"/></label>').appendTo(this.elements.controls).find('input').change(function(ev)
{
planner.round_trip = $(this).is(':checked');
planner.update_route();
});
this.json_container = $('<input type="hidden" name="json" />');
$('<form action="" method="POST"><input type="text" name="name" value="Route name" /><input type="submit" /></form>').append(this.json_container).append(CSRF).appendTo(this.elements.controls);
};
/**
* Clears route and markers from the map
*/
Planner.prototype.clear = function()
{
// Clear all markers, avoiding leaks
for (var i = 0; i < this.markers.length; i++)
{
this.markers[i].setMap();
}
this.markers = [];
// Clear route
if (this.route_renderer)
this.route_renderer.setMap();
this.route_renderer = null;
this.update_info();
};
/**
* Updates the route information view
*/
Planner.prototype.update_info = function()
{
this.elements.info.html('');
if (!this.route_renderer)
{
$('<span></span>').text("No route entered").appendTo(this.elements.info);
this.json_container.val('{"waypoints":[]}');
}
else
{
var distance = 0;
for (var i = 0; i < this.route.legs.length; i++)
{
distance += this.route.legs[i].distance.value;
}
$('<span></span>').text("Route distance: " + distance + 'm').appendTo(this.elements.info);
var waypoints = [];
for (var i = 0; i < this.markers.length; i++)
{
waypoints.push({'lat': this.markers[i].getPosition().lat(), 'lng': this.markers[i].getPosition().lng()});
}
this.json_container.val(JSON.stringify({'waypoints': waypoints,
'distance': distance})); // TODO: Enter score here
}
}
/**
* Loads a route from a json representation
* @param {JSON} json the json representation to load
*/
Planner.prototype.load = function(json)
{
var data = JSON.parse(json);
console.log(data);
this.elements.controls.find('input[name="name"]').val(data['name']);
var planner = this;
for (var i = 0; i < data.waypoints.length; i++)
{
// TODO: Create marker function
var marker_options = {'position': new google.maps.LatLng(data.waypoints[i].lat, data.waypoints[i].lng),
'draggable': true};
var marker = new google.maps.Marker(marker_options);
planner.markers.push(marker);
planner.update_route(planner);
// Event to remove said waypoint
google.maps.event.addListener(marker, 'rightclick', function(ev)
{
marker.setMap();
var index = planner.markers.indexOf(marker);
if (index >= 0)
planner.markers.splice(index, 1);
planner.update_route(planner);
});
// Event on drag
google.maps.event.addListener(marker, 'dragend', function(ev)
{
planner.update_route(planner);
});
}
console.log(this.markers);
this.update_route();
}
|
Created a unified way of adding markers to the planner
|
runweb/static/js/planner.js
|
Created a unified way of adding markers to the planner
|
<ide><path>unweb/static/js/planner.js
<ide> {
<ide> if (planner.markers.length >= 9)
<ide> return;
<del>
<del> // TODO: Create marker function
<del> var marker_options = {'position': ev.latLng,
<del> 'draggable': true};
<del>
<del> var marker = new google.maps.Marker(marker_options);
<del> planner.markers.push(marker);
<del> planner.update_route(planner);
<del>
<del> // Event to remove said waypoint
<del> google.maps.event.addListener(marker, 'rightclick', function(ev)
<del> {
<del> marker.setMap();
<del>
<del> var index = planner.markers.indexOf(marker);
<del> if (index >= 0)
<del> planner.markers.splice(index, 1);
<del>
<del> planner.update_route(planner);
<del> });
<del>
<del> // Event on drag
<del> google.maps.event.addListener(marker, 'dragend', function(ev)
<del> {
<del> planner.update_route(planner);
<del> });
<add>
<add> planner.add_marker(ev.latLng)
<ide> });
<ide> };
<ide>
<ide> */
<ide> Planner.prototype.load = function(json)
<ide> {
<add> // TODO: Validate json
<ide> var data = JSON.parse(json);
<ide> console.log(data);
<ide> this.elements.controls.find('input[name="name"]').val(data['name']);
<ide>
<del> var planner = this;
<ide> for (var i = 0; i < data.waypoints.length; i++)
<del> {
<del> // TODO: Create marker function
<del> var marker_options = {'position': new google.maps.LatLng(data.waypoints[i].lat, data.waypoints[i].lng),
<del> 'draggable': true};
<del>
<del> var marker = new google.maps.Marker(marker_options);
<del> planner.markers.push(marker);
<del> planner.update_route(planner);
<del>
<del> // Event to remove said waypoint
<del> google.maps.event.addListener(marker, 'rightclick', function(ev)
<del> {
<del> marker.setMap();
<del>
<del> var index = planner.markers.indexOf(marker);
<del> if (index >= 0)
<del> planner.markers.splice(index, 1);
<del>
<del> planner.update_route(planner);
<del> });
<del>
<del> // Event on drag
<del> google.maps.event.addListener(marker, 'dragend', function(ev)
<del> {
<del> planner.update_route(planner);
<del> });
<del> }
<add> this.add_marker(new google.maps.LatLng(data.waypoints[i].lat, data.waypoints[i].lng))
<ide>
<ide> console.log(this.markers);
<ide> this.update_route();
<ide> }
<add>
<add>/*
<add> * Adds a marker to the map, adding relevant events and updates the directions
<add> * @param {google.maps.LatLng} position The LatLng object representing the position to add the marker
<add> */
<add>Planner.prototype.add_marker = function(position)
<add>{
<add> // Allow 'this' reference through callbacks
<add> var planner = this;
<add>
<add> var marker_options = {'position': position,
<add> 'draggable': true};
<add>
<add> var marker = new google.maps.Marker(marker_options);
<add> this.markers.push(marker);
<add> this.update_route(planner);
<add>
<add> // Event to remove said waypoint
<add> google.maps.event.addListener(marker, 'rightclick', function(ev)
<add> {
<add> marker.setMap();
<add>
<add> var index = planner.markers.indexOf(marker);
<add> if (index >= 0)
<add> planner.markers.splice(index, 1);
<add>
<add> planner.update_route(planner);
<add> });
<add>
<add> // Event on drag
<add> google.maps.event.addListener(marker, 'dragend', function(ev)
<add> {
<add> planner.update_route(planner);
<add> });
<add>};
|
|
Java
|
apache-2.0
|
270196425a919beed69b79de9d8f6a07a0f0cf35
| 0 |
surya-janani/sakai,Fudan-University/sakai,udayg/sakai,wfuedu/sakai,rodriguezdevera/sakai,clhedrick/sakai,duke-compsci290-spring2016/sakai,kwedoff1/sakai,puramshetty/sakai,bkirschn/sakai,conder/sakai,ouit0408/sakai,frasese/sakai,rodriguezdevera/sakai,introp-software/sakai,zqian/sakai,introp-software/sakai,willkara/sakai,willkara/sakai,hackbuteer59/sakai,zqian/sakai,ktakacs/sakai,joserabal/sakai,zqian/sakai,willkara/sakai,rodriguezdevera/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,joserabal/sakai,buckett/sakai-gitflow,willkara/sakai,lorenamgUMU/sakai,pushyamig/sakai,puramshetty/sakai,whumph/sakai,kwedoff1/sakai,conder/sakai,joserabal/sakai,ktakacs/sakai,rodriguezdevera/sakai,frasese/sakai,noondaysun/sakai,willkara/sakai,conder/sakai,liubo404/sakai,pushyamig/sakai,joserabal/sakai,bzhouduke123/sakai,kingmook/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,frasese/sakai,frasese/sakai,clhedrick/sakai,OpenCollabZA/sakai,ouit0408/sakai,bkirschn/sakai,pushyamig/sakai,OpenCollabZA/sakai,ktakacs/sakai,colczr/sakai,buckett/sakai-gitflow,puramshetty/sakai,clhedrick/sakai,Fudan-University/sakai,lorenamgUMU/sakai,liubo404/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,zqian/sakai,wfuedu/sakai,joserabal/sakai,bkirschn/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,liubo404/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,zqian/sakai,noondaysun/sakai,whumph/sakai,tl-its-umich-edu/sakai,introp-software/sakai,hackbuteer59/sakai,bzhouduke123/sakai,surya-janani/sakai,buckett/sakai-gitflow,udayg/sakai,OpenCollabZA/sakai,tl-its-umich-edu/sakai,kingmook/sakai,pushyamig/sakai,joserabal/sakai,surya-janani/sakai,udayg/sakai,zqian/sakai,zqian/sakai,whumph/sakai,kwedoff1/sakai,noondaysun/sakai,hackbuteer59/sakai,wfuedu/sakai,buckett/sakai-gitflow,ktakacs/sakai,tl-its-umich-edu/sakai,surya-janani/sakai,kwedoff1/sakai,clhedrick/sakai,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,colczr/sakai,kingmook/sakai,frasese/sakai,rodriguezdevera/sakai,whumph/sakai,joserabal/sakai,clhedrick/sakai,conder/sakai,kwedoff1/sakai,ktakacs/sakai,noondaysun/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,Fudan-University/sakai,kwedoff1/sakai,udayg/sakai,pushyamig/sakai,hackbuteer59/sakai,kingmook/sakai,colczr/sakai,bkirschn/sakai,joserabal/sakai,pushyamig/sakai,clhedrick/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,wfuedu/sakai,whumph/sakai,OpenCollabZA/sakai,liubo404/sakai,ktakacs/sakai,pushyamig/sakai,buckett/sakai-gitflow,ktakacs/sakai,kwedoff1/sakai,zqian/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,ktakacs/sakai,Fudan-University/sakai,liubo404/sakai,frasese/sakai,conder/sakai,udayg/sakai,colczr/sakai,rodriguezdevera/sakai,Fudan-University/sakai,conder/sakai,colczr/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,ouit0408/sakai,introp-software/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,ouit0408/sakai,pushyamig/sakai,lorenamgUMU/sakai,surya-janani/sakai,willkara/sakai,willkara/sakai,puramshetty/sakai,udayg/sakai,ouit0408/sakai,bkirschn/sakai,ouit0408/sakai,puramshetty/sakai,introp-software/sakai,puramshetty/sakai,whumph/sakai,udayg/sakai,introp-software/sakai,kingmook/sakai,kingmook/sakai,lorenamgUMU/sakai,frasese/sakai,bkirschn/sakai,lorenamgUMU/sakai,bkirschn/sakai,noondaysun/sakai,wfuedu/sakai,introp-software/sakai,lorenamgUMU/sakai,Fudan-University/sakai,ouit0408/sakai,liubo404/sakai,ouit0408/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,Fudan-University/sakai,wfuedu/sakai,kingmook/sakai,bzhouduke123/sakai,surya-janani/sakai,Fudan-University/sakai,surya-janani/sakai,conder/sakai,clhedrick/sakai,wfuedu/sakai,hackbuteer59/sakai,bzhouduke123/sakai,puramshetty/sakai,kingmook/sakai,noondaysun/sakai,puramshetty/sakai,udayg/sakai,OpenCollabZA/sakai,surya-janani/sakai,liubo404/sakai,colczr/sakai,willkara/sakai,conder/sakai,kwedoff1/sakai,bkirschn/sakai,OpenCollabZA/sakai,liubo404/sakai,frasese/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,whumph/sakai
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.component.kerberos.user;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.user.api.UserDirectoryProvider;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.util.StringUtil;
import sun.misc.BASE64Encoder;
/**
* <p>
* KerberosUserDirectoryProvider is a UserDirectoryProvider that authenticates usernames using Kerberos.
* </p>
* <p>
* For more information on configuration, see the README.txt file
* <p>
*/
public class KerberosUserDirectoryProvider implements UserDirectoryProvider
{
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(KerberosUserDirectoryProvider.class);
/**********************************************************************************************************************************************************************************************************************************************************
* Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************************************************************************************************
* Configuration options and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Configuration: Domain */
protected String m_domain = "domain.tld";
/**
* Configuration: Domain Name (for E-Mail Addresses)
*
* @param domain
* The domain in the form of "domain.tld"
*/
public void setDomain(String domain)
{
m_domain = domain;
}
/** Configuration: LoginContext */
protected String m_logincontext = "KerberosAuthentication";
/**
* Configuration: Authentication Name
*
* @param logincontext
* The context to be used from the login.config file - default "KerberosAuthentication"
*/
public void setLoginContext(String logincontext)
{
m_logincontext = logincontext;
}
/** Configuration: RequireLocalAccount */
protected boolean m_requirelocalaccount = true;
/**
* Configuration: Require Local Account
*
* @param requirelocalaccount
* Determine if a local account is required for user to authenticate - default "true"
*/
public void setRequireLocalAccount(Boolean requirelocalaccount)
{
m_requirelocalaccount = requirelocalaccount.booleanValue();
}
/** Configuration: KnownUserMsg */
protected String m_knownusermsg = "Integrity check on decrypted field failed";
/**
* Configuration: Kerberos Error Message
*
* @param knownusermsg
* Start of error returned for bad logins by known users - default is from RFC 1510
*/
public void setKnownUserMsg(String knownusermsg)
{
m_knownusermsg = knownusermsg;
}
/** Configuration: Cachettl */
protected int m_cachettl = 5 * 60 * 1000;
/**
* Configuration: Cache TTL
*
* @param cachettl
* Time (in milliseconds) to cache authenticated usernames - default is 300000 ms (5 minutes)
*/
public void setCachettl(int cachettl)
{
m_cachettl = cachettl;
}
/**
* Hash table for auth caching
*/
private Hashtable users = new Hashtable();
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
try
{
// Full paths only from the file
String kerberoskrb5conf = ServerConfigurationService.getString("provider.kerberos.krb5.conf", null);
String kerberosauthloginconfig = ServerConfigurationService.getString("provider.kerberos.auth.login.config", null);
boolean kerberosshowconfig = ServerConfigurationService.getBoolean("provider.kerberos.showconfig", false);
String sakaihomepath = System.getProperty("sakai.home");
// if locations are configured in sakai.properties, use them in place of the current system locations
// if the location specified exists and is readable, use full absolute path
// otherwise, try file path relative to sakai.home
// if files are readable use the, otherwise print warning and use system defaults
if (kerberoskrb5conf != null)
{
if (new File(kerberoskrb5conf).canRead())
{
System.setProperty("java.security.krb5.conf", kerberoskrb5conf);
}
else if (new File(sakaihomepath + kerberoskrb5conf).canRead())
{
System.setProperty("java.security.krb5.conf", sakaihomepath + kerberoskrb5conf);
}
else
{
M_log.warn(this + ".init(): Cannot set krb5conf location");
kerberoskrb5conf = null;
}
}
if (kerberosauthloginconfig != null)
{
if (new File(kerberosauthloginconfig).canRead())
{
System.setProperty("java.security.auth.login.config", kerberosauthloginconfig);
}
else if (new File(sakaihomepath + kerberosauthloginconfig).canRead())
{
System.setProperty("java.security.auth.login.config", sakaihomepath + kerberosauthloginconfig);
}
else
{
M_log.warn(this + ".init(): Cannot set kerberosauthloginconfig location");
kerberosauthloginconfig = null;
}
}
M_log.info(this + ".init()" + " Domain=" + m_domain + " LoginContext=" + m_logincontext + " RequireLocalAccount="
+ m_requirelocalaccount + " KnownUserMsg=" + m_knownusermsg + " CacheTTL=" + m_cachettl);
// show the whole config if set
// system locations will read NULL if not set (system defaults will be used)
if (kerberosshowconfig)
{
M_log.info(this + ".init()" + " SakaiHome=" + sakaihomepath + " SakaiPropertyKrb5Conf=" + kerberoskrb5conf
+ " SakaiPropertyAuthLoginConfig=" + kerberosauthloginconfig + " SystemPropertyKrb5Conf="
+ System.getProperty("java.security.krb5.conf") + " SystemPropertyAuthLoginConfig="
+ System.getProperty("java.security.auth.login.config"));
}
}
catch (Throwable t)
{
M_log.warn(this + ".init(): ", t);
}
} // init
/**
* Returns to uninitialized state. You can use this method to release resources thet your Service allocated when Turbine shuts down.
*/
public void destroy()
{
M_log.info(this + ".destroy()");
} // destroy
/**********************************************************************************************************************************************************************************************************************************************************
* UserDirectoryProvider implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* See if a user by this id exists.
*
* @param userId
* The user id string.
* @return true if a user by this id exists, false if not.
*/
public boolean userExists(String userId)
{
if (m_requirelocalaccount) return false;
boolean knownKerb = userKnownToKerberos(userId);
M_log.info("userExists: " + userId + " Kerberos: " + knownKerb);
return knownKerb;
} // userExists
/**
* Access a user object. Update the object with the information found.
*
* @param edit
* The user object (id is set) to fill in.
* @return true if the user object was found and information updated, false if not.
*/
public boolean getUser(UserEdit edit)
{
if (!userExists(edit.getEid())) return false;
edit.setEmail(edit.getEid() + "@" + m_domain);
edit.setType("kerberos");
return true;
} // getUser
/**
* Access a collection of UserEdit objects; if the user is found, update the information, otherwise remove the UserEdit object from the collection.
*
* @param users
* The UserEdit objects (with id set) to fill in or remove.
*/
public void getUsers(Collection users)
{
for (Iterator i = users.iterator(); i.hasNext();)
{
UserEdit user = (UserEdit) i.next();
if (!getUser(user))
{
i.remove();
}
}
}
/**
* Find a user object who has this email address. Update the object with the information found.
*
* @param email
* The email address string.
* @return true if the user object was found and information updated, false if not.
*/
public boolean findUserByEmail(UserEdit edit, String email)
{
// lets not get messed up with spaces or cases
String test = email.toLowerCase().trim();
// if the email ends with "domain.tld" (even if it's from [email protected])
// use the local part as a user id.
if (!test.endsWith(m_domain)) return false;
// split the string once at the first "@"
String parts[] = StringUtil.splitFirst(test, "@");
edit.setEid(parts[0]);
return getUser(edit);
} // findUserByEmail
/**
* Authenticate a user / password. Check for an "valid, previously authenticated" user in in-memory table.
*
* @param id
* The user id.
* @param edit
* The UserEdit matching the id to be authenticated (and updated) if we have one.
* @param password
* The password.
* @return true if authenticated, false if not.
*/
public boolean authenticateUser(String userId, UserEdit edit, String password)
{
// The in-memory caching mechanism is implemented here
// try to get user from in-memory hashtable
try
{
UserData existingUser = (UserData) users.get(userId);
boolean authUser = false;
String hpassword = encodeSHA(password);
// Check for user in in-memory hashtable. To be a "valid, previously authenticated" user,
// 3 conditions must be met:
//
// 1) an entry for the userId must exist in the cache
// 2) the last usccessful authentication was < cachettl milliseconds ago
// 3) the one-way hash of the entered password must be equivalent to what is stored in the cache
//
// If these conditions are not, the authentication is performed via JAAS and, if sucessful, a new entry is created
if (existingUser == null || (System.currentTimeMillis() - existingUser.getTimeStamp()) > m_cachettl
|| !(existingUser.getHpw().equals(hpassword)))
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateUser(): user " + userId + " not in table, querying Kerberos");
boolean authKerb = authenticateKerberos(userId, password);
// if authentication succeeds, create entry for authenticated user in cache;
// otherwise, remove any entries for this user from cache
if (authKerb)
{
if (M_log.isDebugEnabled())
M_log.debug("authenticateUser(): putting authenticated user (" + userId + ") in table for caching");
UserData u = new UserData(); // create entry for authenticated user in cache
u.setId(userId);
u.setHpw(hpassword);
u.setTimeStamp(System.currentTimeMillis());
users.put(userId, u); // put entry for authenticated user into cache
}
else
{
users.remove(userId);
}
authUser = authKerb;
}
else
{
if (M_log.isDebugEnabled())
M_log.debug("authenticateUser(): found authenticated user (" + existingUser.getId() + ") in table");
authUser = true;
}
return authUser;
}
catch (Exception e)
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateUser(): exception: " + e);
return false;
}
} // authenticateUser
/**
* {@inheritDoc}
*/
public void destroyAuthentication()
{
}
/**
* Will this provider update user records on successful authentication? If so, the UserDirectoryService will cause these updates to be stored.
*
* @return true if the user record may be updated after successful authentication, false if not.
*/
public boolean updateUserAfterAuthentication()
{
return false;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Kerberos stuff
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Authenticate the user id and pw with Kerberos.
*
* @param user
* The user id.
* @param password
* the user supplied password.
* @return true if successful, false if not.
*/
protected boolean authenticateKerberos(String user, String pw)
{
// assure some length to the password
if ((pw == null) || (pw.length() == 0)) return false;
// Obtain a LoginContext, needed for authentication. Tell it
// to use the LoginModule implementation specified by the
// appropriate entry in the JAAS login configuration
// file and to also use the specified CallbackHandler.
LoginContext lc = null;
try
{
SakaiCallbackHandler t = new SakaiCallbackHandler();
t.setId(user);
t.setPw(pw);
lc = new LoginContext(m_logincontext, t);
}
catch (LoginException le)
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateKerberos(): " + le.toString());
return false;
}
catch (SecurityException se)
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateKerberos(): " + se.toString());
return false;
}
try
{
// attempt authentication
lc.login();
lc.logout();
if (M_log.isDebugEnabled()) M_log.debug("authenticateKerberos(" + user + ", pw): Kerberos auth success");
return true;
}
catch (LoginException le)
{
if (M_log.isDebugEnabled())
M_log.debug("authenticateKerberos(" + user + ", pw): Kerberos auth failed: " + le.toString());
return false;
}
} // authenticateKerberos
/**
* Check if the user id is known to kerberos.
*
* @param user
* The user id.
* @return true if successful, false if not.
*/
private boolean userKnownToKerberos(String user)
{
// use a dummy password
String pw = "dummy";
// Obtain a LoginContext, needed for authentication.
// Tell it to use the LoginModule implementation specified
// in the JAAS login configuration file and to use
// use the specified CallbackHandler.
LoginContext lc = null;
try
{
SakaiCallbackHandler t = new SakaiCallbackHandler();
t.setId(user);
t.setPw(pw);
lc = new LoginContext(m_logincontext, t);
}
catch (LoginException le)
{
if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(): " + le.toString());
return false;
}
catch (SecurityException se)
{
if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(): " + se.toString());
return false;
}
try
{
// attempt authentication
lc.login();
lc.logout();
if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(" + user + "): Kerberos auth success");
return true;
}
catch (LoginException le)
{
String msg = le.getMessage();
// if this is the message, the user was good, the password was bad
if (msg.startsWith(m_knownusermsg))
{
if (M_log.isDebugEnabled()) M_log.debug("userKnownToKerberos(" + user + "): Kerberos user known (bad pw)");
return true;
}
// the other message is when the user is bad:
if (M_log.isDebugEnabled()) M_log.debug("userKnownToKerberos(" + user + "): Kerberos user unknown or invalid");
return false;
}
} // userKnownToKerberos
/**
* Inner Class SakaiCallbackHandler Get the user id and password information for authentication purpose. This can be used by a JAAS application to instantiate a CallbackHandler.
*
* @see javax.security.auth.callback
*/
protected class SakaiCallbackHandler implements CallbackHandler
{
private String m_id;
private String m_pw;
/** constructor */
public SakaiCallbackHandler()
{
m_id = new String("");
m_pw = new String("");
} // SakaiCallbackHandler
/**
* Handles the specified set of callbacks.
*
* @param callbacks
* the callbacks to handle
* @throws IOException
* if an input or output error occurs.
* @throws UnsupportedCallbackException
* if the callback is not an instance of NameCallback or PasswordCallback
*/
public void handle(Callback[] callbacks) throws java.io.IOException, UnsupportedCallbackException
{
ConfirmationCallback confirmation = null;
for (int i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof TextOutputCallback)
{
if (M_log.isDebugEnabled()) M_log.debug("SakaiCallbackHandler: TextOutputCallback");
}
else if (callbacks[i] instanceof NameCallback)
{
NameCallback nc = (NameCallback) callbacks[i];
String result = getId();
if (result.equals(""))
{
result = nc.getDefaultName();
}
nc.setName(result);
}
else if (callbacks[i] instanceof PasswordCallback)
{
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword(getPw());
}
else if (callbacks[i] instanceof ConfirmationCallback)
{
if (M_log.isDebugEnabled()) M_log.debug("SakaiCallbackHandler: ConfirmationCallback");
}
else
{
throw new UnsupportedCallbackException(callbacks[i], "SakaiCallbackHandler: Unrecognized Callback");
}
}
} // handle
void setId(String id)
{
m_id = id;
} // setId
private String getId()
{
return m_id;
} // getid
void setPw(String pw)
{
m_pw = pw;
} // setPw
private char[] getPw()
{
return m_pw.toCharArray();
} // getPw
} // SakaiCallbackHandler
/**
* {@inheritDoc}
*/
public boolean authenticateWithProviderFirst(String id)
{
return false;
}
/**
* {@inheritDoc}
*/
public boolean createUserRecord(String id)
{
return false;
}
/**
* <p>
* Helper class for storing user data in an in-memory cache
* </p>
*/
class UserData
{
String id;
String hpw;
long timeStamp;
/**
* @return Returns the id.
*/
public String getId()
{
return id;
}
/**
* @param id
* The id to set.
*/
public void setId(String id)
{
this.id = id;
}
/**
* @param hpw
* hashed pw to put in.
*/
public void setHpw(String hpw)
{
this.hpw = hpw;
}
/**
* @return Returns the hashed password.
*/
public String getHpw()
{
return hpw;
}
/**
* @return Returns the timeStamp.
*/
public long getTimeStamp()
{
return timeStamp;
}
/**
* @param timeStamp
* The timeStamp to set.
*/
public void setTimeStamp(long timeStamp)
{
this.timeStamp = timeStamp;
}
} // UserData class
/**
* <p>
* Hash string for storage in a cache using SHA
* </p>
*
* @param UTF-8
* string
* @return encoded hash of string
*/
private synchronized String encodeSHA(String plaintext)
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(plaintext.getBytes("UTF-8"));
byte raw[] = md.digest();
String hash = (new BASE64Encoder()).encode(raw);
return hash;
}
catch (Exception e)
{
M_log.warn("encodeSHA(): exception: " + e);
return null;
}
} // encodeSHA
} // KerberosUserDirectoryProvider
|
providers/kerberos/src/java/org/sakaiproject/component/kerberos/user/KerberosUserDirectoryProvider.java
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.component.kerberos.user;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.user.api.UserDirectoryProvider;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.util.StringUtil;
import sun.misc.BASE64Encoder;
/**
* <p>
* KerberosUserDirectoryProvider is UserDirectoryProvider that authenticates usernames using Kerberos.
* </p>
* <p>
* For more information on configuration, see the README.txt file
* <p>
*/
public class KerberosUserDirectoryProvider implements UserDirectoryProvider
{
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(KerberosUserDirectoryProvider.class);
/**********************************************************************************************************************************************************************************************************************************************************
* Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************************************************************************************************
* Configuration options and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Configuration: Domain */
protected String m_domain = "domain.tld";
/**
* Configuration: Domain Name (for E-Mail Addresses)
*
* @param domain
* The domain in the form of "domain.tld"
*/
public void setDomain(String domain)
{
m_domain = domain;
}
/** Configuration: LoginContext */
protected String m_logincontext = "KerberosAuthentication";
/**
* Configuration: Authentication Name
*
* @param logincontext
* The context to be used from the login.config file - default "KerberosAuthentication"
*/
public void setLoginContext(String logincontext)
{
m_logincontext = logincontext;
}
/** Configuration: RequireLocalAccount */
protected boolean m_requirelocalaccount = true;
/**
* Configuration: Require Local Account
*
* @param requirelocalaccount
* Determine if a local account is required for user to authenticate - default "true"
*/
public void setRequireLocalAccount(Boolean requirelocalaccount)
{
m_requirelocalaccount = requirelocalaccount.booleanValue();
}
/** Configuration: KnownUserMsg */
protected String m_knownusermsg = "Integrity check on decrypted field failed";
/**
* Configuration: Kerberos Error Message
*
* @param knownusermsg
* Start of error returned for bad logins by known users - default is from RFC 1510
*/
public void setKnownUserMsg(String knownusermsg)
{
m_knownusermsg = knownusermsg;
}
/** Configuration: Cachettl */
protected int m_cachettl = 5 * 60 * 1000;
/**
* Configuration: Cache TTL
*
* @param cachettl
* Time (in milliseconds) to cache authenticated usernames - default is 300000 ms (5 minutes)
*/
public void setCachettl(int cachettl)
{
m_cachettl = cachettl;
}
/**
* Hash table for auth caching
*/
private Hashtable users = new Hashtable();
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
try
{
// Full paths only from the file
String kerberoskrb5conf = ServerConfigurationService.getString("provider.kerberos.krb5.conf", null);
String kerberosauthloginconfig = ServerConfigurationService.getString("provider.kerberos.auth.login.config", null);
boolean kerberosshowconfig = ServerConfigurationService.getBoolean("provider.kerberos.showconfig", false);
String sakaihomepath = System.getProperty("sakai.home");
// if locations are configured in sakai.properties, use them in place of the current system locations
// if the location specified exists and is readable, use full absolute path
// otherwise, try file path relative to sakai.home
// if files are readable use the, otherwise print warning and use system defaults
if (kerberoskrb5conf != null)
{
if (new File(kerberoskrb5conf).canRead())
{
System.setProperty("java.security.krb5.conf", kerberoskrb5conf);
}
else if (new File(sakaihomepath + kerberoskrb5conf).canRead())
{
System.setProperty("java.security.krb5.conf", sakaihomepath + kerberoskrb5conf);
}
else
{
M_log.warn(this + ".init(): Cannot set krb5conf location");
kerberoskrb5conf = null;
}
}
if (kerberosauthloginconfig != null)
{
if (new File(kerberosauthloginconfig).canRead())
{
System.setProperty("java.security.auth.login.config", kerberosauthloginconfig);
}
else if (new File(sakaihomepath + kerberosauthloginconfig).canRead())
{
System.setProperty("java.security.auth.login.config", sakaihomepath + kerberosauthloginconfig);
}
else
{
M_log.warn(this + ".init(): Cannot set kerberosauthloginconfig location");
kerberosauthloginconfig = null;
}
}
M_log.info(this + ".init()" + " Domain=" + m_domain + " LoginContext=" + m_logincontext + " RequireLocalAccount="
+ m_requirelocalaccount + " KnownUserMsg=" + m_knownusermsg + " CacheTTL=" + m_cachettl);
// show the whole config if set
// system locations will read NULL if not set (system defaults will be used)
if (kerberosshowconfig)
{
M_log.info(this + ".init()" + " SakaiHome=" + sakaihomepath + " SakaiPropertyKrb5Conf=" + kerberoskrb5conf
+ " SakaiPropertyAuthLoginConfig=" + kerberosauthloginconfig + " SystemPropertyKrb5Conf="
+ System.getProperty("java.security.krb5.conf") + " SystemPropertyAuthLoginConfig="
+ System.getProperty("java.security.auth.login.config"));
}
}
catch (Throwable t)
{
M_log.warn(this + ".init(): ", t);
}
} // init
/**
* Returns to uninitialized state. You can use this method to release resources thet your Service allocated when Turbine shuts down.
*/
public void destroy()
{
M_log.info(this + ".destroy()");
} // destroy
/**********************************************************************************************************************************************************************************************************************************************************
* UserDirectoryProvider implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* See if a user by this id exists.
*
* @param userId
* The user id string.
* @return true if a user by this id exists, false if not.
*/
public boolean userExists(String userId)
{
if (m_requirelocalaccount) return false;
boolean knownKerb = userKnownToKerberos(userId);
M_log.info("userExists: " + userId + " Kerberos: " + knownKerb);
return knownKerb;
} // userExists
/**
* Access a user object. Update the object with the information found.
*
* @param edit
* The user object (id is set) to fill in.
* @return true if the user object was found and information updated, false if not.
*/
public boolean getUser(UserEdit edit)
{
if (!userExists(edit.getEid())) return false;
edit.setEmail(edit.getEid() + "@" + m_domain);
edit.setType("kerberos");
return true;
} // getUser
/**
* Access a collection of UserEdit objects; if the user is found, update the information, otherwise remove the UserEdit object from the collection.
*
* @param users
* The UserEdit objects (with id set) to fill in or remove.
*/
public void getUsers(Collection users)
{
for (Iterator i = users.iterator(); i.hasNext();)
{
UserEdit user = (UserEdit) i.next();
if (!getUser(user))
{
i.remove();
}
}
}
/**
* Find a user object who has this email address. Update the object with the information found.
*
* @param email
* The email address string.
* @return true if the user object was found and information updated, false if not.
*/
public boolean findUserByEmail(UserEdit edit, String email)
{
// lets not get messed up with spaces or cases
String test = email.toLowerCase().trim();
// if the email ends with "umich.edu" (even if it's from [email protected])
// use the local part as a user id.
if (!test.endsWith(m_domain)) return false;
// split the string once at the first "@"
String parts[] = StringUtil.splitFirst(test, "@");
edit.setId(parts[0]);
return getUser(edit);
} // findUserByEmail
/**
* Authenticate a user / password. Check for an "valid, previously authenticated" user in in-memory table.
*
* @param id
* The user id.
* @param edit
* The UserEdit matching the id to be authenticated (and updated) if we have one.
* @param password
* The password.
* @return true if authenticated, false if not.
*/
public boolean authenticateUser(String userId, UserEdit edit, String password)
{
// The in-memory caching mechanism is implemented here
// try to get user from in-memory hashtable
try
{
UserData existingUser = (UserData) users.get(userId);
boolean authUser = false;
String hpassword = encodeSHA(password);
// Check for user in in-memory hashtable. To be a "valid, previously authenticated" user,
// 3 conditions must be met:
//
// 1) an entry for the userId must exist in the cache
// 2) the last usccessful authentication was < cachettl milliseconds ago
// 3) the one-way hash of the entered password must be equivalent to what is stored in the cache
//
// If these conditions are not, the authentication is performed via JAAS and, if sucessful, a new entry is created
if (existingUser == null || (System.currentTimeMillis() - existingUser.getTimeStamp()) > m_cachettl
|| !(existingUser.getHpw().equals(hpassword)))
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateUser(): user " + userId + " not in table, querying Kerberos");
boolean authKerb = authenticateKerberos(userId, password);
// if authentication succeeds, create entry for authenticated user in cache;
// otherwise, remove any entries for this user from cache
if (authKerb)
{
if (M_log.isDebugEnabled())
M_log.debug("authenticateUser(): putting authenticated user (" + userId + ") in table for caching");
UserData u = new UserData(); // create entry for authenticated user in cache
u.setId(userId);
u.setHpw(hpassword);
u.setTimeStamp(System.currentTimeMillis());
users.put(userId, u); // put entry for authenticated user into cache
}
else
{
users.remove(userId);
}
authUser = authKerb;
}
else
{
if (M_log.isDebugEnabled())
M_log.debug("authenticateUser(): found authenticated user (" + existingUser.getId() + ") in table");
authUser = true;
}
return authUser;
}
catch (Exception e)
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateUser(): exception: " + e);
return false;
}
} // authenticateUser
/**
* {@inheritDoc}
*/
public void destroyAuthentication()
{
}
/**
* Will this provider update user records on successful authentication? If so, the UserDirectoryService will cause these updates to be stored.
*
* @return true if the user record may be updated after successful authentication, false if not.
*/
public boolean updateUserAfterAuthentication()
{
return false;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Kerberos stuff
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Authenticate the user id and pw with Kerberos.
*
* @param user
* The user id.
* @param password
* the user supplied password.
* @return true if successful, false if not.
*/
protected boolean authenticateKerberos(String user, String pw)
{
// assure some length to the password
if ((pw == null) || (pw.length() == 0)) return false;
// Obtain a LoginContext, needed for authentication. Tell it
// to use the LoginModule implementation specified by the
// appropriate entry in the JAAS login configuration
// file and to also use the specified CallbackHandler.
LoginContext lc = null;
try
{
SakaiCallbackHandler t = new SakaiCallbackHandler();
t.setId(user);
t.setPw(pw);
lc = new LoginContext(m_logincontext, t);
}
catch (LoginException le)
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateKerberos(): " + le.toString());
return false;
}
catch (SecurityException se)
{
if (M_log.isDebugEnabled()) M_log.debug("authenticateKerberos(): " + se.toString());
return false;
}
try
{
// attempt authentication
lc.login();
lc.logout();
if (M_log.isDebugEnabled()) M_log.debug("authenticateKerberos(" + user + ", pw): Kerberos auth success");
return true;
}
catch (LoginException le)
{
if (M_log.isDebugEnabled())
M_log.debug("authenticateKerberos(" + user + ", pw): Kerberos auth failed: " + le.toString());
return false;
}
} // authenticateKerberos
/**
* Check if the user id is known to kerberos.
*
* @param user
* The user id.
* @return true if successful, false if not.
*/
private boolean userKnownToKerberos(String user)
{
// use a dummy password
String pw = "dummy";
// Obtain a LoginContext, needed for authentication.
// Tell it to use the LoginModule implementation specified
// in the JAAS login configuration file and to use
// use the specified CallbackHandler.
LoginContext lc = null;
try
{
SakaiCallbackHandler t = new SakaiCallbackHandler();
t.setId(user);
t.setPw(pw);
lc = new LoginContext(m_logincontext, t);
}
catch (LoginException le)
{
if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(): " + le.toString());
return false;
}
catch (SecurityException se)
{
if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(): " + se.toString());
return false;
}
try
{
// attempt authentication
lc.login();
lc.logout();
if (M_log.isDebugEnabled()) M_log.debug("useKnownToKerberos(" + user + "): Kerberos auth success");
return true;
}
catch (LoginException le)
{
String msg = le.getMessage();
// if this is the message, the user was good, the password was bad
if (msg.startsWith(m_knownusermsg))
{
if (M_log.isDebugEnabled()) M_log.debug("userKnownToKerberos(" + user + "): Kerberos user known (bad pw)");
return true;
}
// the other message is when the user is bad:
if (M_log.isDebugEnabled()) M_log.debug("userKnownToKerberos(" + user + "): Kerberos user unknown or invalid");
return false;
}
} // userKnownToKerberos
/**
* Inner Class SakaiCallbackHandler Get the user id and password information for authentication purpose. This can be used by a JAAS application to instantiate a CallbackHandler.
*
* @see javax.security.auth.callback
*/
protected class SakaiCallbackHandler implements CallbackHandler
{
private String m_id;
private String m_pw;
/** constructor */
public SakaiCallbackHandler()
{
m_id = new String("");
m_pw = new String("");
} // SakaiCallbackHandler
/**
* Handles the specified set of callbacks.
*
* @param callbacks
* the callbacks to handle
* @throws IOException
* if an input or output error occurs.
* @throws UnsupportedCallbackException
* if the callback is not an instance of NameCallback or PasswordCallback
*/
public void handle(Callback[] callbacks) throws java.io.IOException, UnsupportedCallbackException
{
ConfirmationCallback confirmation = null;
for (int i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof TextOutputCallback)
{
if (M_log.isDebugEnabled()) M_log.debug("SakaiCallbackHandler: TextOutputCallback");
}
else if (callbacks[i] instanceof NameCallback)
{
NameCallback nc = (NameCallback) callbacks[i];
String result = getId();
if (result.equals(""))
{
result = nc.getDefaultName();
}
nc.setName(result);
}
else if (callbacks[i] instanceof PasswordCallback)
{
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword(getPw());
}
else if (callbacks[i] instanceof ConfirmationCallback)
{
if (M_log.isDebugEnabled()) M_log.debug("SakaiCallbackHandler: ConfirmationCallback");
}
else
{
throw new UnsupportedCallbackException(callbacks[i], "SakaiCallbackHandler: Unrecognized Callback");
}
}
} // handle
void setId(String id)
{
m_id = id;
} // setId
private String getId()
{
return m_id;
} // getid
void setPw(String pw)
{
m_pw = pw;
} // setPw
private char[] getPw()
{
return m_pw.toCharArray();
} // getPw
} // SakaiCallbackHandler
/**
* {@inheritDoc}
*/
public boolean authenticateWithProviderFirst(String id)
{
return false;
}
/**
* {@inheritDoc}
*/
public boolean createUserRecord(String id)
{
return false;
}
/**
* <p>
* Helper class for storing user data in an in-memory cache
* </p>
*/
class UserData
{
String id;
String hpw;
long timeStamp;
/**
* @return Returns the id.
*/
public String getId()
{
return id;
}
/**
* @param id
* The id to set.
*/
public void setId(String id)
{
this.id = id;
}
/**
* @param hpw
* hashed pw to put in.
*/
public void setHpw(String hpw)
{
this.hpw = hpw;
}
/**
* @return Returns the hashed password.
*/
public String getHpw()
{
return hpw;
}
/**
* @return Returns the timeStamp.
*/
public long getTimeStamp()
{
return timeStamp;
}
/**
* @param timeStamp
* The timeStamp to set.
*/
public void setTimeStamp(long timeStamp)
{
this.timeStamp = timeStamp;
}
} // UserData class
/**
* <p>
* Hash string for storage in a cache using SHA
* </p>
*
* @param UTF-8
* string
* @return encoded hash of string
*/
private synchronized String encodeSHA(String plaintext)
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(plaintext.getBytes("UTF-8"));
byte raw[] = md.digest();
String hash = (new BASE64Encoder()).encode(raw);
return hash;
}
catch (Exception e)
{
M_log.warn("encodeSHA(): exception: " + e);
return null;
}
} // encodeSHA
} // KerberosUserDirectoryProvider
|
fix missing eid/id separation oversight
fix one innocuous documentation typo
remove reference to umich.edu
SAK-7348
http://bugs.sakaiproject.org/jira/browse/SAK-7348
git-svn-id: 8c080e3f2d70e2035171982369b83e325695f964@17982 66ffb92e-73f9-0310-93c1-f5514f145a0a
|
providers/kerberos/src/java/org/sakaiproject/component/kerberos/user/KerberosUserDirectoryProvider.java
|
fix missing eid/id separation oversight fix one innocuous documentation typo remove reference to umich.edu SAK-7348 http://bugs.sakaiproject.org/jira/browse/SAK-7348
|
<ide><path>roviders/kerberos/src/java/org/sakaiproject/component/kerberos/user/KerberosUserDirectoryProvider.java
<ide>
<ide> /**
<ide> * <p>
<del> * KerberosUserDirectoryProvider is UserDirectoryProvider that authenticates usernames using Kerberos.
<add> * KerberosUserDirectoryProvider is a UserDirectoryProvider that authenticates usernames using Kerberos.
<ide> * </p>
<ide> * <p>
<ide> * For more information on configuration, see the README.txt file
<ide> // lets not get messed up with spaces or cases
<ide> String test = email.toLowerCase().trim();
<ide>
<del> // if the email ends with "umich.edu" (even if it's from [email protected])
<add> // if the email ends with "domain.tld" (even if it's from [email protected])
<ide> // use the local part as a user id.
<ide>
<ide> if (!test.endsWith(m_domain)) return false;
<ide>
<ide> // split the string once at the first "@"
<ide> String parts[] = StringUtil.splitFirst(test, "@");
<del> edit.setId(parts[0]);
<add> edit.setEid(parts[0]);
<ide> return getUser(edit);
<ide>
<ide> } // findUserByEmail
|
|
JavaScript
|
mit
|
c98689f8df3e7ead7bc0b14778f78699814026f9
| 0 |
denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase
|
/**
* Views for the story viewer Backbone application
*/
Namespace('storybase.viewer');
// Translations for interface text
Globalize.addCultureInfo('en', {
messages: {
"Topic Map": "Topic Map",
"How Can You Help?": "How Can You Help?"
}
});
Globalize.addCultureInfo('es', {
messages: {
"Topic Map": "Mapa Temático",
"How Can You Help?": "How Can You Help?"
}
});
// Container view for the viewer application.
// It delegates rendering and events for the entire app to views
// rendering more specific "widgets"
storybase.viewer.views.ViewerApp = Backbone.View.extend({
// Initialize the view
initialize: function() {
this.sections = this.options.sections;
this.story = this.options.story;
this.navigationView = new storybase.viewer.views.StoryNavigation({
sections: this.options.sections
});
this.headerView = new storybase.viewer.views.StoryHeader();
this.setSection(this.sections.at(0), {showActiveSection: false});
_.bindAll(this, 'handleScroll');
$(window).scroll(this.handleScroll);
},
// Add the view's container element to the DOM and render the sub-views
render: function() {
this.$el.addClass(this.elClass);
this.$('footer').append(this.navigationView.el);
this.navigationView.render();
this.$('.summary').show();
this.$('.section').show();
return this;
},
// Update the active story section in the sub-views
updateSubviewSections: function() {
this.navigationView.setSection(this.activeSection);
this.headerView.setSection(this.activeSection);
},
// Show the active section
showActiveSection: function() {
throw "showActiveSection() is not implemented";
},
// Set the active story section
setSection: function(section, options) {
options = typeof options !== 'undefined' ? options : {};
var showActiveSection = options.hasOwnProperty('showActiveSection') ? options.showActiveSection : true;
this.activeSection = section;
if (showActiveSection) {
this.showActiveSection();
}
this.updateSubviewSections();
},
// Like setSection(), but takes a section ID as an argument instead of
// a Section model instance object
setSectionById: function(id) {
this.setSection(this.sections.get(id));
},
// Convenience method to get the element for the active section
activeSectionEl: function() {
return this.$('#' + this.activeSection.id);
},
// Event handler for scroll event
handleScroll: function(e) {
// Do nothing. Subclasses might want to implement this to do some work
}
});
// View for the story viewer header.
// Updates the section heading title when the active section changes
storybase.viewer.views.StoryHeader = Backbone.View.extend({
el: 'header',
render: function() {
var $titleEl = this.$el.find('.section-title').first();
if ($titleEl.length == 0) {
$titleEl = $('<h2 class="section-title">');
this.$el.append($titleEl);
}
$titleEl.text(this.section.get('title'));
return this;
},
setSection: function(section) {
this.section = section;
this.render();
}
});
// View to provide previous/next buttons to navigate between sections
storybase.viewer.views.StoryNavigation = Backbone.View.extend({
tagName: 'nav',
className: 'story-nav',
initialize: function() {
this.section = null;
this.sections = this.options.sections;
if (this.options.hasOwnProperty('addlLinks')) {
this.addlLinks = this.options.addlLinks.map(function(link) {
return {
text: link.text,
id: link.id,
href: link.hasOwnProperty('href') ? link.href: '#'
}
});
}
else {
this.addlLinks = [];
}
},
render: function() {
var context = {};
if (this.section) {
context.next_section = this.sections.get(
this.section.get('next_section_id'));
context.previous_section = this.sections.get(
this.section.get('previous_section_id'));
}
context.addl_links = this.addlLinks;
this.$el.html(ich.navigationTemplate(context));
return this;
},
setSection: function(section) {
this.section = section;
this.render();
}
});
// Interative visualization of a spider story structure
storybase.viewer.views.Spider = Backbone.View.extend({
events: {
"hover g.node": "hoverSectionNode"
},
initialize: function() {
this.sections = this.options.sections;
this.insertBefore = this.options.insertBefore;
this.subtractHeight = this.options.subtractHeight;
this.subtractWidth = this.options.subtractWidth;
this.activeSection = null;
// The id for the visualization's wrapper element
this.visId = 'spider-vis';
this.maxDepth = null;
this.sectionsAtDepth = [];
this.maxSectionsAtDepth = 0;
this.walkSectionHierarchy(0, this.sections.at(0));
},
// Walk the section hierarchy to build a sense of its "shape"
walkSectionHierarchy: function(depth, section) {
if (this.maxDepth == null ||
depth > this.maxDepth) {
this.maxDepth = depth;
}
if (this.sectionsAtDepth[depth] === undefined) {
this.sectionsAtDepth[depth] = 1;
}
else {
this.sectionsAtDepth[depth]++;
}
if (this.sectionsAtDepth[depth] > this.maxSectionsAtDepth) {
this.maxSectionsAtDepth = this.sectionsAtDepth[depth];
}
var $this = this;
_.each(section.get('children'), function(childId) {
$this.walkSectionHierarchy(depth + 1, $this.sections.get(childId));
});
},
// Return the visualization wrapper element
visEl: function() {
return this.$('#' + this.visId).first();
},
setSection: function(section) {
this.activeSection = section;
this.highlightSectionNode(this.activeSection.id);
},
highlightSectionNode: function(sectionId) {
d3.selectAll('g.node').classed('active', false);
d3.select('g.node.section-' + sectionId).classed('active', true);
},
// Get the dimensions of the visualization's wrapper element
getVisDimensions: function() {
// We have to calculate the dimensions relative to the window rather than
// the parent element because the parent element is really tall as it
// also contains the (hidden) section content. It seems there should be
// a better way to do this, but I don't know it.
width = $(window).width();
height = $(window).height();
_.each(this.subtractWidth, function(selector) {
width -= $(selector).outerWidth();
});
_.each(this.subtractHeight, function(selector) {
height -= $(selector).outerHeight();
});
return {
width: width,
height: height
};
},
// Get the radius of the tree
getTreeRadius: function(width, height) {
return (this.maxSectionsAtDepth == 1 ? _.max([width, height]) : _.min([width, height])) * .66;
},
render: function() {
var $this = this;
var elId = this.$el.attr('id');
var dimensions = this.getVisDimensions();
var treeRadius = this.getTreeRadius(dimensions.width, dimensions.height);
var vis = d3.select("#" + elId).insert("svg", this.insertBefore)
.attr("id", this.visId)
.attr("width", dimensions.width)
.attr("height", dimensions.height)
.attr("style", "float:left")
.append("g");
var rootSection = this.sections.at(0).populateChildren();
var tree = d3.layout.tree()
.size([360, treeRadius - 120])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
var diagonal = d3.svg.diagonal.radial()
.projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
var nodes = tree.nodes(rootSection);
// Fix x coordinate (angle) when each level has only one child
// In this case d.x = NaN which breakins things
nodes = _.map(nodes, function(node) {
node.x = $this.maxSectionsAtDepth == 1 ? 90 : node.x;
return node;
});
var links = tree.links(nodes);
var link = vis.selectAll("path.link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = vis.selectAll("g.node")
.data(nodes)
.enter().append("g")
.attr('class', function(d) {
return "node section-" + d.id;
})
.attr("transform", function(d) {
var transform = "";
if (d.depth > 0) {
transform += "rotate(" + (d.x - 90) + ")";
}
transform += "translate(" + d.y + ")";
return transform;
});
node.append("circle")
.attr("r", 15);
node.append("text")
.attr("x", function(d) {
if (d.depth == 0) { return 20; }
return d.x < 180 ? 20 : -20;
})
.attr("y", ".31em")
.attr("text-anchor", function(d) {
if (d.depth == 0) { return "start"; }
return d.x < 180 ? "start" : "end"; })
.attr("transform", function(d) {
var rotation = 0;
if ($this.maxSectionsAtDepth == 1) {
rotation = 315;
}
else if (d.depth > 0) {
rotation = 90 - d.x;
}
return "rotate(" + rotation + ")";
})
.text(function(d) { return d.get('title'); });
// Center the tree within the viewport
var treeBBox = vis[0][0].getBBox();
var translateX = (0 - treeBBox.x) + ((dimensions.width - treeBBox.width) / 2);
var translateY = (0 - treeBBox.y) + ((dimensions.height - treeBBox.height) / 2);
vis.attr("transform", "translate(" + translateX + ", " + translateY + ")");
},
// Event handler for hovering over a section node
// Changes the cursor to a "pointer" style icon to indicate that
// the nodes are clickable.
hoverSectionNode: function(e) {
e.currentTarget.style.cursor = 'pointer';
},
});
// Master view that shows a story in a linear fashion
storybase.viewer.views.LinearViewerApp = storybase.viewer.views.ViewerApp.extend({
elClass: 'linear',
// Get the position, from the top of the winder, of the lower edge of the
// header
headerBottom: function() {
return headerHeight = this.$('header').outerHeight()
},
footerTop: function() {
return this.$('footer').offset().top;
},
// Show the active section
showActiveSection: function() {
var sectionTop = this.$('#' + this.activeSection.id).offset().top;
this._preventScrollEvent = true;
var headerBottom = this.headerBottom();
var scrollBy = Math.ceil(sectionTop - this.headerBottom());
$(window).scrollTop(scrollBy);
},
// Return the element of the last visible story section
getLastVisibleSectionEl: function() {
var visibleSections = [];
var numSections = this.$('section').length;
for (var i = 0; i < numSections; i++) {
var $section = this.$('section').eq(i);
var sectionTop = $section.offset().top;
var sectionBottom = sectionTop + $section.outerHeight();
if (sectionTop >= this.headerBottom() &&
sectionBottom <= this.footerTop()) {
visibleSections.push($section);
}
}
return _.last(visibleSections);
},
// Event handler for scroll event
handleScroll: function(e) {
var newSection = this.activeSection;
if (this._preventScrollEvent !== true) {
if ($(window).scrollTop() == 0) {
// At the top of the window. Set the active section to the
// first section
newSection = this.sections.first();
}
else {
var $lastVisibleSectionEl = this.getLastVisibleSectionEl();
if ($lastVisibleSectionEl) {
var lastVisibleSection = this.sections.get($lastVisibleSectionEl.attr('id'));
if (lastVisibleSection != this.activeSection) {
newSection = lastVisibleSection;
}
}
}
this.setSection(newSection, {showActiveSection: false});
storybase.viewer.router.navigate("sections/" + newSection.id,
{trigger: false});
}
this._preventScrollEvent = false;
}
});
// Master view that shows the story structure visualization initially
storybase.viewer.views.SpiderViewerApp = storybase.viewer.views.ViewerApp.extend({
elClass: 'spider',
events: {
"click #topic-map": "clickTopicMapLink",
"click g.node": "clickSectionNode"
},
initialize: function() {
this.sections = this.options.sections;
this.story = this.options.story;
this.navigationView = new storybase.viewer.views.StoryNavigation({
sections: this.options.sections,
addlLinks: [{text: Globalize.localize("Topic Map"), id: 'topic-map'}]
});
this.headerView = new storybase.viewer.views.StoryHeader();
this.initialView = new storybase.viewer.views.Spider({
el: this.$('#body'),
sections: this.options.sections,
insertBefore: '.section',
subtractWidth: ['.summary'],
subtractHeight: ['header', 'footer']
});
},
render: function() {
this.$el.addClass(this.elClass);
this.$('footer').append(this.navigationView.el);
this.navigationView.render();
this.initialView.render();
this.$('.summary').show();
// Hide all the section content initially
this.$('.section').hide();
return this;
},
// Show the active section
showActiveSection: function() {
// Hide the summary
this.$('.summary').hide();
// Hide all sections other than the active one
this.$('.section').hide();
this.$('#' + this.activeSection.id).show();
// Hide the visualization
this.initialView.$('svg').hide();
},
// Update the active story section in the sub-views
updateSubviewSections: function() {
this.navigationView.setSection(this.activeSection);
this.headerView.setSection(this.activeSection);
this.initialView.setSection(this.activeSection);
},
// Event handler for clicks on a section node
clickSectionNode: function(e) {
var node = d3.select(e.currentTarget);
var sectionId = node.data()[0].id;
this.initialView.visEl().hide();
// TODO: I'm not sure if this is the best way to access the router
// I don't like global variables, but passing it as an argument
// makes for a weird circular dependency between the master view/
// router.
storybase.viewer.router.navigate("sections/" + sectionId,
{trigger: true});
},
// Event handler for clicking the "Topic Map" link
clickTopicMapLink: function(e) {
var activeSectionEl = this.activeSectionEl();
if (activeSectionEl !== null) {
var visEl = this.initialView.visEl();
if (visEl.css('display') == 'none') {
this.initialView.visEl().show();
}
else {
this.initialView.visEl().hide();
}
this.$('.summary').toggle();
}
}
});
// Get the appropriate master view based on the story structure type
storybase.viewer.views.getViewerApp = function(structureType, options) {
if (structureType == 'linear') {
return new storybase.viewer.views.LinearViewerApp(options);
}
else if (structureType == 'spider') {
return new storybase.viewer.views.SpiderViewerApp(options);
}
else {
throw "Unknown story structure type '" + structureType + "'";
}
};
|
static/js/viewer/views.js
|
/**
* Views for the story viewer Backbone application
*/
Namespace('storybase.viewer');
// Translations for interface text
Globalize.addCultureInfo('en', {
messages: {
"Topic Map": "Topic Map",
"How Can You Help?": "How Can You Help?"
}
});
Globalize.addCultureInfo('es', {
messages: {
"Topic Map": "Mapa Temático",
"How Can You Help?": "How Can You Help?"
}
});
// Container view for the viewer application.
// It delegates rendering and events for the entire app to views
// rendering more specific "widgets"
storybase.viewer.views.ViewerApp = Backbone.View.extend({
// Initialize the view
initialize: function() {
this.sections = this.options.sections;
this.story = this.options.story;
this.navigationView = new storybase.viewer.views.StoryNavigation({
sections: this.options.sections
});
this.headerView = new storybase.viewer.views.StoryHeader();
this.setSection(this.sections.at(0), {showActiveSection: false});
_.bindAll(this, 'handleScroll');
$(window).scroll(this.handleScroll);
},
// Add the view's container element to the DOM and render the sub-views
render: function() {
this.$el.addClass(this.elClass);
this.$('footer').append(this.navigationView.el);
this.navigationView.render();
this.$('.summary').show();
this.$('.section').show();
return this;
},
// Update the active story section in the sub-views
updateSubviewSections: function() {
this.navigationView.setSection(this.activeSection);
this.headerView.setSection(this.activeSection);
},
// Show the active section
showActiveSection: function() {
throw "showActiveSection() is not implemented";
},
// Set the active story section
setSection: function(section, options) {
options = typeof options !== 'undefined' ? options : {};
var showActiveSection = options.hasOwnProperty('showActiveSection') ? options.showActiveSection : true;
this.activeSection = section;
if (showActiveSection) {
this.showActiveSection();
}
this.updateSubviewSections();
},
// Like setSection(), but takes a section ID as an argument instead of
// a Section model instance object
setSectionById: function(id) {
this.setSection(this.sections.get(id));
},
// Convenience method to get the element for the active section
activeSectionEl: function() {
return this.$('#' + this.activeSection.id);
},
// Event handler for scroll event
handleScroll: function(e) {
// Do nothing. Subclasses might want to implement this to do some work
}
});
// View for the story viewer header.
// Updates the section heading title when the active section changes
storybase.viewer.views.StoryHeader = Backbone.View.extend({
el: 'header',
render: function() {
var $titleEl = this.$el.find('.section-title').first();
if ($titleEl.length == 0) {
$titleEl = $('<h2 class="section-title">');
this.$el.append($titleEl);
}
$titleEl.text(this.section.get('title'));
return this;
},
setSection: function(section) {
this.section = section;
this.render();
}
});
// View to provide previous/next buttons to navigate between sections
storybase.viewer.views.StoryNavigation = Backbone.View.extend({
tagName: 'nav',
className: 'story-nav',
initialize: function() {
this.section = null;
this.sections = this.options.sections;
if (this.options.hasOwnProperty('addlLinks')) {
this.addlLinks = this.options.addlLinks.map(function(link) {
return {
text: link.text,
id: link.id,
href: link.hasOwnProperty('href') ? link.href: '#'
}
});
}
else {
this.addlLinks = [];
}
},
render: function() {
var context = {};
if (this.section) {
context.next_section = this.sections.get(
this.section.get('next_section_id'));
context.previous_section = this.sections.get(
this.section.get('previous_section_id'));
}
context.addl_links = this.addlLinks;
this.$el.html(ich.navigationTemplate(context));
return this;
},
setSection: function(section) {
this.section = section;
this.render();
}
});
// Interative visualization of a spider story structure
storybase.viewer.views.Spider = Backbone.View.extend({
events: {
"hover g.node": "hoverSectionNode"
},
initialize: function() {
this.sections = this.options.sections;
this.insertBefore = this.options.insertBefore;
this.subtractHeight = this.options.subtractHeight;
this.subtractWidth = this.options.subtractWidth;
this.activeSection = null;
// The id for the visualization's wrapper element
this.visId = 'spider-vis';
this.maxDepth = null;
this.sectionsAtDepth = [];
this.maxSectionsAtDepth = 0;
this.walkSectionHierarchy(0, this.sections.at(0));
},
// Walk the section hierarchy to build a sense of its "shape"
walkSectionHierarchy: function(depth, section) {
if (this.maxDepth == null ||
depth > this.maxDepth) {
this.maxDepth = depth;
}
if (this.sectionsAtDepth[depth] === undefined) {
this.sectionsAtDepth[depth] = 1;
}
else {
this.sectionsAtDepth[depth]++;
}
if (this.sectionsAtDepth[depth] > this.maxSectionsAtDepth) {
this.maxSectionsAtDepth = this.sectionsAtDepth[depth];
}
var $this = this;
_.each(section.get('children'), function(childId) {
$this.walkSectionHierarchy(depth + 1, $this.sections.get(childId));
});
},
// Return the visualization wrapper element
visEl: function() {
return this.$('#' + this.visId).first();
},
setSection: function(section) {
this.activeSection = section;
this.highlightSectionNode(this.activeSection.id);
},
highlightSectionNode: function(sectionId) {
d3.selectAll('g.node').classed('active', false);
d3.select('g.node.section-' + sectionId).classed('active', true);
},
// Get the dimensions of the visualization's wrapper element
getVisDimensions: function() {
// We have to calculate the dimensions relative to the window rather than
// the parent element because the parent element is really tall as it
// also contains the (hidden) section content. It seems there should be
// a better way to do this, but I don't know it.
width = $(window).width();
height = $(window).height();
_.each(this.subtractWidth, function(selector) {
width -= $(selector).outerWidth();
});
_.each(this.subtractHeight, function(selector) {
height -= $(selector).outerHeight();
});
return {
width: width,
height: height
};
},
// Get the radius of the tree
getTreeRadius: function(width, height) {
return (this.maxSectionsAtDepth == 1 ? _.max([width, height]) : _.min([width, height])) * .66;
},
render: function() {
var $this = this;
var elId = this.$el.attr('id');
var dimensions = this.getVisDimensions();
var treeRadius = this.getTreeRadius(dimensions.width, dimensions.height);
var vis = d3.select("#" + elId).insert("svg", this.insertBefore)
.attr("id", this.visId)
.attr("width", dimensions.width)
.attr("height", dimensions.height)
.attr("style", "float:left")
.append("g");
var rootSection = this.sections.at(0).populateChildren();
var tree = d3.layout.tree()
.size([360, treeRadius - 120])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
var diagonal = d3.svg.diagonal.radial()
.projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
var nodes = tree.nodes(rootSection);
// Fix x coordinate (angle) when each level has only one child
// In this case d.x = NaN which breakins things
nodes = _.map(nodes, function(node) {
node.x = $this.maxSectionsAtDepth == 1 ? 90 : node.x;
return node;
});
var links = tree.links(nodes);
var link = vis.selectAll("path.link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = vis.selectAll("g.node")
.data(nodes)
.enter().append("g")
.attr('class', function(d) {
return "node section-" + d.id;
})
.attr("transform", function(d) {
var transform = "";
if (d.depth > 0) {
transform += "rotate(" + (d.x - 90) + ")";
}
transform += "translate(" + d.y + ")";
return transform;
});
node.append("circle")
.attr("r", 15);
node.append("text")
.attr("x", function(d) {
if (d.depth == 0) { return 20; }
return d.x < 180 ? 20 : -20;
})
.attr("y", ".31em")
.attr("text-anchor", function(d) {
if (d.depth == 0) { return "start"; }
return d.x < 180 ? "start" : "end"; })
.attr("transform", function(d) {
var rotation = 0;
if ($this.maxSectionsAtDepth == 1) {
rotation = 315;
}
else if (d.depth > 0) {
rotation = 90 - d.x;
}
return "rotate(" + rotation + ")";
})
.text(function(d) { return d.get('title'); });
// Center the tree within the viewport
var treeBBox = vis[0][0].getBBox();
var translateX = (0 - treeBBox.x) + ((dimensions.width - treeBBox.width) / 2);
var translateY = (0 - treeBBox.y) + ((dimensions.height - treeBBox.height) / 2);
vis.attr("transform", "translate(" + translateX + ", " + translateY + ")");
},
// Event handler for hovering over a section node
// Changes the cursor to a "pointer" style icon to indicate that
// the nodes are clickable.
hoverSectionNode: function(e) {
e.currentTarget.style.cursor = 'pointer';
},
});
// Master view that shows a story in a linear fashion
storybase.viewer.views.LinearViewerApp = storybase.viewer.views.ViewerApp.extend({
elClass: 'linear',
// Get the position, from the top of the winder, of the lower edge of the
// header
headerBottom: function() {
return this.$('header').offset().top + this.$('header').outerHeight();
},
footerTop: function() {
return this.$('footer').offset().top;
},
// Show the active section
showActiveSection: function() {
var sectionTop = this.$('#' + this.activeSection.id).offset().top;
this._preventScrollEvent = true;
$(window).scrollTop(sectionTop - this.headerBottom());
},
// Return the element of the last visible story section
getLastVisibleSectionEl: function() {
var visibleSections = [];
var numSections = this.$('section').length;
for (var i = 0; i < numSections; i++) {
var $section = this.$('section').eq(i);
var sectionTop = $section.offset().top;
var sectionBottom = sectionTop + $section.outerHeight();
if (sectionTop >= this.headerBottom() &&
sectionBottom <= this.footerTop()) {
visibleSections.push($section);
}
}
return _.last(visibleSections);
},
// Event handler for scroll event
handleScroll: function(e) {
var newSection = this.activeSection;
if (this._preventScrollEvent !== true) {
if ($(window).scrollTop() == 0) {
// At the top of the window. Set the active section to the
// first section
newSection = this.sections.first();
}
else {
var $lastVisibleSectionEl = this.getLastVisibleSectionEl();
if ($lastVisibleSectionEl) {
var lastVisibleSection = this.sections.get($lastVisibleSectionEl.attr('id'));
if (lastVisibleSection != this.activeSection) {
newSection = lastVisibleSection;
}
}
}
this.setSection(newSection, {showActiveSection: false});
storybase.viewer.router.navigate("sections/" + newSection.id,
{trigger: false});
}
this._preventScrollEvent = false;
}
});
// Master view that shows the story structure visualization initially
storybase.viewer.views.SpiderViewerApp = storybase.viewer.views.ViewerApp.extend({
elClass: 'spider',
events: {
"click #topic-map": "clickTopicMapLink",
"click g.node": "clickSectionNode"
},
initialize: function() {
this.sections = this.options.sections;
this.story = this.options.story;
this.navigationView = new storybase.viewer.views.StoryNavigation({
sections: this.options.sections,
addlLinks: [{text: Globalize.localize("Topic Map"), id: 'topic-map'}]
});
this.headerView = new storybase.viewer.views.StoryHeader();
this.initialView = new storybase.viewer.views.Spider({
el: this.$('#body'),
sections: this.options.sections,
insertBefore: '.section',
subtractWidth: ['.summary'],
subtractHeight: ['header', 'footer']
});
},
render: function() {
this.$el.addClass(this.elClass);
this.$('footer').append(this.navigationView.el);
this.navigationView.render();
this.initialView.render();
this.$('.summary').show();
// Hide all the section content initially
this.$('.section').hide();
return this;
},
// Show the active section
showActiveSection: function() {
// Hide the summary
this.$('.summary').hide();
// Hide all sections other than the active one
this.$('.section').hide();
this.$('#' + this.activeSection.id).show();
// Hide the visualization
this.initialView.$('svg').hide();
},
// Update the active story section in the sub-views
updateSubviewSections: function() {
this.navigationView.setSection(this.activeSection);
this.headerView.setSection(this.activeSection);
this.initialView.setSection(this.activeSection);
},
// Event handler for clicks on a section node
clickSectionNode: function(e) {
var node = d3.select(e.currentTarget);
var sectionId = node.data()[0].id;
this.initialView.visEl().hide();
// TODO: I'm not sure if this is the best way to access the router
// I don't like global variables, but passing it as an argument
// makes for a weird circular dependency between the master view/
// router.
storybase.viewer.router.navigate("sections/" + sectionId,
{trigger: true});
},
// Event handler for clicking the "Topic Map" link
clickTopicMapLink: function(e) {
var activeSectionEl = this.activeSectionEl();
if (activeSectionEl !== null) {
var visEl = this.initialView.visEl();
if (visEl.css('display') == 'none') {
this.initialView.visEl().show();
}
else {
this.initialView.visEl().hide();
}
this.$('.summary').toggle();
}
}
});
// Get the appropriate master view based on the story structure type
storybase.viewer.views.getViewerApp = function(structureType, options) {
if (structureType == 'linear') {
return new storybase.viewer.views.LinearViewerApp(options);
}
else if (structureType == 'spider') {
return new storybase.viewer.views.SpiderViewerApp(options);
}
else {
throw "Unknown story structure type '" + structureType + "'";
}
};
|
Fixed scrolling by links in linear story viewer.
For some reason, I was calculating the scroll using the header's offset,
which was changing (even though it's absolutely positioned, hmmm). Just
using the outer height of the header works great.
|
static/js/viewer/views.js
|
Fixed scrolling by links in linear story viewer.
|
<ide><path>tatic/js/viewer/views.js
<ide> // Get the position, from the top of the winder, of the lower edge of the
<ide> // header
<ide> headerBottom: function() {
<del> return this.$('header').offset().top + this.$('header').outerHeight();
<add> return headerHeight = this.$('header').outerHeight()
<ide> },
<ide>
<ide> footerTop: function() {
<ide> showActiveSection: function() {
<ide> var sectionTop = this.$('#' + this.activeSection.id).offset().top;
<ide> this._preventScrollEvent = true;
<del> $(window).scrollTop(sectionTop - this.headerBottom());
<add> var headerBottom = this.headerBottom();
<add> var scrollBy = Math.ceil(sectionTop - this.headerBottom());
<add> $(window).scrollTop(scrollBy);
<ide> },
<ide>
<ide> // Return the element of the last visible story section
|
|
Java
|
apache-2.0
|
3907d5feeb0d4b125e072d5d498d6e97c43cec0c
| 0 |
wso2/product-mdm,dilee/product-emm,Malintha/product-emm,Kamidu/product-mdm,wso2/product-mdm,wso2/product-mdm,madhawap/product-emm,Malintha/product-emm,dilee/product-emm,dilee/product-mdm,charithag/product-emm,madhawap/product-emm,Kamidu/product-mdm,Kamidu/product-mdm,Malintha/product-emm,dilee/product-emm,dilee/product-mdm,milanperera/product-mdm,dilee/product-mdm,Malintha/product-emm,charithag/product-emm,Kamidu/product-mdm,madhawap/product-emm,dilee/product-emm,dilee/product-mdm,wso2/product-mdm,charithag/product-emm,milanperera/product-mdm,milanperera/product-mdm,charithag/product-emm,madhawap/product-emm,milanperera/product-mdm
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DetailedDeviceEntry;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DeviceCountByGroupEntry;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import org.wso2.carbon.mdm.beans.DashboardGadgetDataWrapper;
import org.wso2.carbon.mdm.beans.DashboardPaginationGadgetDataWrapper;
import org.wso2.carbon.mdm.exception.Message;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Produces({"application/json"})
@Consumes({"application/json"})
public class Dashboard {
private static Log log = LogFactory.getLog(Dashboard.class);
// Constants related to Dashboard filtering
public static final String CONNECTIVITY_STATUS = "connectivity-status";
public static final String POTENTIAL_VULNERABILITY = "potential-vulnerability";
public static final String NON_COMPLIANT_FEATURE_CODE = "non-compliant-feature-code";
public static final String PLATFORM = "platform";
public static final String OWNERSHIP_TYPE = "ownership";
// Constants related to pagination
public static final String PAGINATION_ENABLED = "pagination-enabled";
public static final String START_INDEX = "start-index";
public static final String RESULT_COUNT = "result-count";
@GET
@Path("device-count-overview")
public Response getOverviewDeviceCounts() throws MDMAPIException {
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
// creating TotalDeviceCount Data Wrapper
DeviceCountByGroupEntry totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve total device count.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
List<Object> overviewDeviceCountsDataWrapper = new ArrayList<>();
overviewDeviceCountsDataWrapper.add(totalDeviceCount);
List<DeviceCountByGroupEntry> deviceCountsByConnectivityStatuses;
try {
deviceCountsByConnectivityStatuses = gadgetDataService.getDeviceCountsByConnectivityStatuses();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve device counts by connectivity statuses.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
for (DeviceCountByGroupEntry entry : deviceCountsByConnectivityStatuses) {
overviewDeviceCountsDataWrapper.add(entry);
}
dashboardGadgetDataWrapper.setContext("Overview-of-device-counts");
dashboardGadgetDataWrapper.setFilteringAttribute(CONNECTIVITY_STATUS);
dashboardGadgetDataWrapper.setData(overviewDeviceCountsDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("device-counts-by-potential-vulnerabilities")
public Response getDeviceCountsByPotentialVulnerabilities() throws MDMAPIException {
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
List<DeviceCountByGroupEntry> deviceCountsByPotentialVulnerabilities;
try {
deviceCountsByPotentialVulnerabilities = gadgetDataService.getDeviceCountsByPotentialVulnerabilities();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve device counts by potential vulnerabilities.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Device-counts-by-potential-vulnerabilities");
dashboardGadgetDataWrapper.setFilteringAttribute(POTENTIAL_VULNERABILITY);
dashboardGadgetDataWrapper.setData(deviceCountsByPotentialVulnerabilities);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("non-compliant-device-counts-by-features")
public Response getNonCompliantDeviceCountsByFeatures(@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount) throws MDMAPIException {
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getNonCompliantDeviceCountsByFeatures(startIndex, resultCount);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a non-compliant set of device counts by features.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a non-compliant set of device counts by features.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
dashboardPaginationGadgetDataWrapper.setContext("Non-compliant-device-counts-by-feature");
dashboardPaginationGadgetDataWrapper.setFilteringAttribute(NON_COMPLIANT_FEATURE_CODE);
dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("device-counts-by-groups")
public Response getDeviceCountsByGroups(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP_TYPE) String ownership) throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating device-Counts-by-platforms Data Wrapper
List<DeviceCountByGroupEntry> deviceCountsByPlatforms;
try {
deviceCountsByPlatforms = gadgetDataService.getDeviceCountsByPlatforms(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of device counts by platforms.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of device counts by platforms.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper1.setContext("Device-counts-by-platforms");
dashboardGadgetDataWrapper1.setFilteringAttribute(PLATFORM);
dashboardGadgetDataWrapper1.setData(deviceCountsByPlatforms);
// creating device-Counts-by-ownership-types Data Wrapper
List<DeviceCountByGroupEntry> deviceCountsByOwnershipTypes;
try {
deviceCountsByOwnershipTypes = gadgetDataService.getDeviceCountsByOwnershipTypes(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of device counts by ownership types.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of device counts by ownership types.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper2.setContext("Device-counts-by-ownership-type");
dashboardGadgetDataWrapper2.setFilteringAttribute(OWNERSHIP_TYPE);
dashboardGadgetDataWrapper2.setData(deviceCountsByOwnershipTypes);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper1);
responsePayload.add(dashboardGadgetDataWrapper2);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("feature-non-compliant-device-counts-by-groups")
public Response getFeatureNonCompliantDeviceCountsByGroups(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP_TYPE) String ownership)
throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating feature-non-compliant-device-Counts-by-platforms Data Wrapper
List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByPlatforms;
try {
featureNonCompliantDeviceCountsByPlatforms = gadgetDataService.
getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant device counts by platforms.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant device counts by platforms.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper1.setContext("Feature-non-compliant-device-counts-by-platforms");
dashboardGadgetDataWrapper1.setFilteringAttribute(PLATFORM);
dashboardGadgetDataWrapper1.setData(featureNonCompliantDeviceCountsByPlatforms);
// creating feature-non-compliant-device-Counts-by-ownership-types Data Wrapper
List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByOwnershipTypes;
try {
featureNonCompliantDeviceCountsByOwnershipTypes = gadgetDataService.
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + "This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant device counts by ownership types.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
"device counts by ownership types.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper2.setContext("Feature-non-compliant-device-counts-by-ownership-types");
dashboardGadgetDataWrapper2.setFilteringAttribute(OWNERSHIP_TYPE);
dashboardGadgetDataWrapper2.setData(featureNonCompliantDeviceCountsByOwnershipTypes);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper1);
responsePayload.add(dashboardGadgetDataWrapper2);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("filtered-device-count-over-total")
public Response getFilteredDeviceCountOverTotal(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP_TYPE) String ownership)
throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating filteredDeviceCount Data Wrapper
DeviceCountByGroupEntry filteredDeviceCount;
try {
filteredDeviceCount = gadgetDataService.getDeviceCount(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered device count over the total.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered device count over the total.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
// creating TotalDeviceCount Data Wrapper
DeviceCountByGroupEntry totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve the total device count over filtered.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
List<Object> filteredDeviceCountOverTotalDataWrapper = new ArrayList<>();
filteredDeviceCountOverTotalDataWrapper.add(filteredDeviceCount);
filteredDeviceCountOverTotalDataWrapper.add(totalDeviceCount);
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Filtered-device-count-over-total");
dashboardGadgetDataWrapper.setFilteringAttribute(null);
dashboardGadgetDataWrapper.setData(filteredDeviceCountOverTotalDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("feature-non-compliant-device-count-over-total")
public Response getFeatureNonCompliantDeviceCountOverTotal(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP_TYPE) String ownership)
throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating featureNonCompliantDeviceCount Data Wrapper
DeviceCountByGroupEntry featureNonCompliantDeviceCount;
try {
featureNonCompliantDeviceCount = gadgetDataService.
getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a feature non-compliant device count over the total.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a feature non-compliant device count over the total.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
// creating TotalDeviceCount Data Wrapper
DeviceCountByGroupEntry totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve the total device count over filtered feature non-compliant.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
List<Object> featureNonCompliantDeviceCountOverTotalDataWrapper = new ArrayList<>();
featureNonCompliantDeviceCountOverTotalDataWrapper.add(featureNonCompliantDeviceCount);
featureNonCompliantDeviceCountOverTotalDataWrapper.add(totalDeviceCount);
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Feature-non-compliant-device-count-over-total");
dashboardGadgetDataWrapper.setFilteringAttribute(null);
dashboardGadgetDataWrapper.setData(featureNonCompliantDeviceCountOverTotalDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("devices-with-details")
public Response getDevicesWithDetails(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
@QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP_TYPE) String ownership,
@QueryParam(PAGINATION_ENABLED) String paginationEnabled,
@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount) throws MDMAPIException {
if (paginationEnabled == null) {
Message message = new Message();
message.setErrorMessage("Missing required query parameter.");
message.setDescription("Pagination-enabled query parameter with value true or false is required.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} else if ("true".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getDevicesWithDetails(filterSet, startIndex, resultCount);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + "This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of devices with details.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
dashboardPaginationGadgetDataWrapper.setContext("Filtered-and-paginated-devices-with-details");
dashboardPaginationGadgetDataWrapper.setFilteringAttribute(null);
dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else if ("false".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
List<DetailedDeviceEntry> devicesWithDetails;
try {
devicesWithDetails = gadgetDataService.getDevicesWithDetails(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of devices with details.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("filtered-devices-with-details");
dashboardGadgetDataWrapper.setFilteringAttribute(null);
dashboardGadgetDataWrapper.setData(devicesWithDetails);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription("Invalid value for query parameter pagination-enabled. " +
"Should be either true or false.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
}
}
@GET
@Path("feature-non-compliant-devices-with-details")
public Response getFeatureNonCompliantDevicesWithDetails(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
@QueryParam(PLATFORM) String platform,
@QueryParam(OWNERSHIP_TYPE) String ownership,
@QueryParam(PAGINATION_ENABLED) String paginationEnabled,
@QueryParam(START_INDEX) int startIndex,
@QueryParam(RESULT_COUNT) int resultCount)
throws MDMAPIException {
if (paginationEnabled == null) {
Message message = new Message();
message.setErrorMessage("Missing required query parameters.");
message.setDescription("Query parameter pagination-enabled with value true or false is required.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} else if ("true".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet, startIndex, resultCount);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant service layer " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant devices with details.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
dashboardPaginationGadgetDataWrapper.setContext("Paginated-feature-non-compliant-devices-with-details");
dashboardPaginationGadgetDataWrapper.setFilteringAttribute(null);
dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else if ("false".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
List<DetailedDeviceEntry> featureNonCompliantDevicesWithDetails;
try {
featureNonCompliantDevicesWithDetails = gadgetDataService.
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription(e.getErrorMessage() + "This was while trying to execute relevant data service " +
"function @ Dashboard API layer to retrieve a filtered set of " +
"feature non-compliant devices with details.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "An internal error occurred while trying to execute relevant data service function " +
"@ Dashboard API layer to retrieve a filtered set of feature " +
"non-compliant set of devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("Feature-non-compliant-devices-with-details");
dashboardGadgetDataWrapper.setFilteringAttribute(null);
dashboardGadgetDataWrapper.setData(featureNonCompliantDevicesWithDetails);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription("Invalid value for " +
"query parameter pagination-enabled. Should be either true or false.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
}
}
}
|
modules/apps/jax-rs/mdm-admin/src/main/java/org/wso2/carbon/mdm/api/Dashboard.java
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.mdm.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import org.wso2.carbon.mdm.beans.DashboardGadgetDataWrapper;
import org.wso2.carbon.mdm.beans.DashboardPaginationGadgetDataWrapper;
import org.wso2.carbon.mdm.exception.Message;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Produces({"application/json"})
@Consumes({"application/json"})
public class Dashboard {
private static Log log = LogFactory.getLog(Dashboard.class);
@GET
@Path("overview-of-devices")
public Response getOverviewDeviceCounts() throws MDMAPIException {
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
// creating TotalDeviceCount Data Wrapper
int totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve total device count.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> totalDeviceCountDataWrapper = new LinkedHashMap<>();
totalDeviceCountDataWrapper.put("group", "total");
totalDeviceCountDataWrapper.put("label", "Total");
totalDeviceCountDataWrapper.put("count", totalDeviceCount);
// creating ActiveDeviceCount Data Wrapper
int activeDeviceCount;
try {
activeDeviceCount = gadgetDataService.getActiveDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve active device count.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> activeDeviceCountDataWrapper = new LinkedHashMap<>();
activeDeviceCountDataWrapper.put("group", "active");
activeDeviceCountDataWrapper.put("label", "Active");
activeDeviceCountDataWrapper.put("count", activeDeviceCount);
// creating inactiveDeviceCount Data Wrapper
int inactiveDeviceCount;
try {
inactiveDeviceCount = gadgetDataService.getInactiveDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve inactive device count.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> inactiveDeviceCountDataWrapper = new LinkedHashMap<>();
inactiveDeviceCountDataWrapper.put("group", "inactive");
inactiveDeviceCountDataWrapper.put("label", "Inactive");
inactiveDeviceCountDataWrapper.put("count", inactiveDeviceCount);
// creating removedDeviceCount Data Wrapper
int removedDeviceCount;
try {
removedDeviceCount = gadgetDataService.getRemovedDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve removed device count.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> removedDeviceCountDataWrapper = new LinkedHashMap<>();
removedDeviceCountDataWrapper.put("group", "removed");
removedDeviceCountDataWrapper.put("label", "Removed");
removedDeviceCountDataWrapper.put("count", removedDeviceCount);
List<Map<String, Object>> overviewDeviceCountsDataWrapper = new ArrayList<>();
overviewDeviceCountsDataWrapper.add(totalDeviceCountDataWrapper);
overviewDeviceCountsDataWrapper.add(activeDeviceCountDataWrapper);
overviewDeviceCountsDataWrapper.add(inactiveDeviceCountDataWrapper);
overviewDeviceCountsDataWrapper.add(removedDeviceCountDataWrapper);
dashboardGadgetDataWrapper.setContext("connectivity-status");
dashboardGadgetDataWrapper.setData(overviewDeviceCountsDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("potential-vulnerabilities")
public Response getVulnerableDeviceCounts() throws MDMAPIException {
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
// creating non-compliant Data Wrapper
int nonCompliantDeviceCount;
try {
nonCompliantDeviceCount = gadgetDataService.getNonCompliantDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve non-compliant device count.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> nonCompliantDeviceCountDataWrapper = new LinkedHashMap<>();
nonCompliantDeviceCountDataWrapper.put("group", "non-compliant");
nonCompliantDeviceCountDataWrapper.put("label", "Non-Compliant");
nonCompliantDeviceCountDataWrapper.put("count", nonCompliantDeviceCount);
// creating unmonitoredDeviceCount Data Wrapper
int unmonitoredDeviceCount;
try {
unmonitoredDeviceCount = gadgetDataService.getUnmonitoredDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve unmonitored device count.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> unmonitoredDeviceCountDataWrapper = new LinkedHashMap<>();
unmonitoredDeviceCountDataWrapper.put("group", "unmonitored");
unmonitoredDeviceCountDataWrapper.put("label", "Unmonitored");
unmonitoredDeviceCountDataWrapper.put("count", unmonitoredDeviceCount);
List<Map<String, Object>> vulnerableDeviceCountsDataWrapper = new ArrayList<>();
vulnerableDeviceCountsDataWrapper.add(nonCompliantDeviceCountDataWrapper);
vulnerableDeviceCountsDataWrapper.add(unmonitoredDeviceCountDataWrapper);
dashboardGadgetDataWrapper.setContext("potential-vulnerability");
dashboardGadgetDataWrapper.setData(vulnerableDeviceCountsDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("non-compliant-by-feature")
public Response getNonCompliantDeviceCountsByFeatures(@QueryParam("start-index") int startIndex,
@QueryParam("result-count") int resultCount, @Context UriInfo uriInfo) throws MDMAPIException {
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getNonCompliantDeviceCountsByFeatures(startIndex, resultCount);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a non-compliant set of device counts by features. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a non-compliant set of device counts by features.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> nonCompliantDeviceCountByFeatureDataWrapper;
List<Map<String, Object>> nonCompliantDeviceCountsByFeaturesDataWrapper = new ArrayList<>();
for (Object listElement : paginationResult.getData()) {
Map entry = (Map<?, ?>) listElement;
nonCompliantDeviceCountByFeatureDataWrapper = new LinkedHashMap<>();
nonCompliantDeviceCountByFeatureDataWrapper.put("group", entry.get("FEATURE_CODE"));
nonCompliantDeviceCountByFeatureDataWrapper.put("label", entry.get("FEATURE_CODE"));
nonCompliantDeviceCountByFeatureDataWrapper.put("count", entry.get("DEVICE_COUNT"));
nonCompliantDeviceCountsByFeaturesDataWrapper.add(nonCompliantDeviceCountByFeatureDataWrapper);
}
dashboardPaginationGadgetDataWrapper.setContext("non-compliant-feature");
dashboardPaginationGadgetDataWrapper.setData(nonCompliantDeviceCountsByFeaturesDataWrapper);
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("device-groupings")
public Response getDeviceGroupingCounts(@QueryParam("connectivity-status") String connectivityStatus,
@QueryParam("potential-vulnerability") String potentialVulnerability,
@QueryParam("platform") String platform,
@QueryParam("ownership") String ownership) throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating device-Counts-by-platforms Data Wrapper
Map<String, Integer> deviceCountsByPlatforms;
try {
deviceCountsByPlatforms = gadgetDataService.getDeviceCountsByPlatforms(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameters.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of device counts by platforms. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of device counts by platforms.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> deviceCountByPlatformDataWrapper;
List<Map<String, Object>> deviceCountsByPlatformsDataWrapper = new ArrayList<>();
for (Map.Entry<String, Integer> entry : deviceCountsByPlatforms.entrySet()) {
deviceCountByPlatformDataWrapper = new LinkedHashMap<>();
deviceCountByPlatformDataWrapper.put("group", entry.getKey());
deviceCountByPlatformDataWrapper.put("label", entry.getKey());
deviceCountByPlatformDataWrapper.put("count", entry.getValue());
deviceCountsByPlatformsDataWrapper.add(deviceCountByPlatformDataWrapper);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper1.setContext("platform");
dashboardGadgetDataWrapper1.setData(deviceCountsByPlatformsDataWrapper);
// creating device-Counts-by-ownership-types Data Wrapper
Map<String, Integer> deviceCountsByOwnershipTypes;
try {
deviceCountsByOwnershipTypes = gadgetDataService.getDeviceCountsByOwnershipTypes(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of device " +
"counts by ownership types. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of device counts by ownership types.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> deviceCountByOwnershipTypeDataWrapper;
List<Map<String, Object>> deviceCountsByOwnershipTypesDataWrapper = new ArrayList<>();
for (Map.Entry<String, Integer> entry : deviceCountsByOwnershipTypes.entrySet()) {
deviceCountByOwnershipTypeDataWrapper = new LinkedHashMap<>();
deviceCountByOwnershipTypeDataWrapper.put("group", entry.getKey());
deviceCountByOwnershipTypeDataWrapper.put("label", entry.getKey());
deviceCountByOwnershipTypeDataWrapper.put("count", entry.getValue());
deviceCountsByOwnershipTypesDataWrapper.add(deviceCountByOwnershipTypeDataWrapper);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper2.setContext("ownership");
dashboardGadgetDataWrapper2.setData(deviceCountsByOwnershipTypesDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper1);
responsePayload.add(dashboardGadgetDataWrapper2);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("feature-non-compliant-device-groupings")
public Response getFeatureNonCompliantDeviceGroupingCounts(@QueryParam("non-compliant-feature") String nonCompliantFeature,
@QueryParam("platform") String platform,
@QueryParam("ownership") String ownership)
throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating feature-non-compliant-device-Counts-by-platforms Data Wrapper
Map<String, Integer> featureNonCompliantDeviceCountsByPlatforms;
try {
featureNonCompliantDeviceCountsByPlatforms = gadgetDataService.
getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeature, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant device " +
"counts by platforms. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant device counts by platforms.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> featureNonCompliantDeviceCountByPlatformDataWrapper;
List<Map<String, Object>> featureNonCompliantDeviceCountsByPlatformsDataWrapper = new ArrayList<>();
for (Map.Entry<String, Integer> entry : featureNonCompliantDeviceCountsByPlatforms.entrySet()) {
featureNonCompliantDeviceCountByPlatformDataWrapper = new LinkedHashMap<>();
featureNonCompliantDeviceCountByPlatformDataWrapper.put("group", entry.getKey());
featureNonCompliantDeviceCountByPlatformDataWrapper.put("label", entry.getKey());
featureNonCompliantDeviceCountByPlatformDataWrapper.put("count", entry.getValue());
featureNonCompliantDeviceCountsByPlatformsDataWrapper.
add(featureNonCompliantDeviceCountByPlatformDataWrapper);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper1.setContext("platform");
dashboardGadgetDataWrapper1.setData(featureNonCompliantDeviceCountsByPlatformsDataWrapper);
// creating feature-non-compliant-device-Counts-by-ownership-types Data Wrapper
Map<String, Integer> featureNonCompliantDeviceCountsByOwnershipTypes;
try {
featureNonCompliantDeviceCountsByOwnershipTypes = gadgetDataService.
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeature, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant device " +
"counts by ownership types. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
"device counts by ownership types.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> featureNonCompliantDeviceCountByOwnershipTypeDataWrapper;
List<Map<String, Object>> featureNonCompliantDeviceCountsByOwnershipTypesDataWrapper = new ArrayList<>();
for (Map.Entry<String, Integer> entry : featureNonCompliantDeviceCountsByOwnershipTypes.entrySet()) {
featureNonCompliantDeviceCountByOwnershipTypeDataWrapper = new LinkedHashMap<>();
featureNonCompliantDeviceCountByOwnershipTypeDataWrapper.put("group", entry.getKey());
featureNonCompliantDeviceCountByOwnershipTypeDataWrapper.put("label", entry.getKey());
featureNonCompliantDeviceCountByOwnershipTypeDataWrapper.put("count", entry.getValue());
featureNonCompliantDeviceCountsByOwnershipTypesDataWrapper.
add(featureNonCompliantDeviceCountByOwnershipTypeDataWrapper);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper2.setContext("ownership");
dashboardGadgetDataWrapper2.setData(featureNonCompliantDeviceCountsByOwnershipTypesDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper1);
responsePayload.add(dashboardGadgetDataWrapper2);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("filtered-devices-over-total")
public Response getFilteredDeviceCountOverTotal(@QueryParam("connectivity-status") String connectivityStatus,
@QueryParam("potential-vulnerability") String potentialVulnerability,
@QueryParam("platform") String platform,
@QueryParam("ownership") String ownership) throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating filteredDeviceCount Data Wrapper
int filteredDeviceCount;
try {
filteredDeviceCount = gadgetDataService.getDeviceCount(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered device count over the total. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered device count over the total.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> filteredDeviceCountDataWrapper = new LinkedHashMap<>();
filteredDeviceCountDataWrapper.put("group", "filtered");
filteredDeviceCountDataWrapper.put("label", "filtered");
filteredDeviceCountDataWrapper.put("count", filteredDeviceCount);
// creating TotalDeviceCount Data Wrapper
int totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve the total device count over filtered.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> totalDeviceCountDataWrapper = new LinkedHashMap<>();
totalDeviceCountDataWrapper.put("group", "total");
totalDeviceCountDataWrapper.put("label", "Total");
totalDeviceCountDataWrapper.put("count", totalDeviceCount);
List<Map<String, Object>> filteredDeviceCountOverTotalDataWrapper = new ArrayList<>();
filteredDeviceCountOverTotalDataWrapper.add(filteredDeviceCountDataWrapper);
filteredDeviceCountOverTotalDataWrapper.add(totalDeviceCountDataWrapper);
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("filtered-device-count-over-total");
dashboardGadgetDataWrapper.setData(filteredDeviceCountOverTotalDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("feature-non-compliant-devices-over-total")
public Response getFeatureNonCompliantDeviceCountOverTotal(@QueryParam("non-compliant-feature") String nonCompliantFeature,
@QueryParam("platform") String platform,
@QueryParam("ownership") String ownership)
throws MDMAPIException {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
// creating featureNonCompliantDeviceCount Data Wrapper
int featureNonCompliantDeviceCount;
try {
featureNonCompliantDeviceCount = gadgetDataService.
getFeatureNonCompliantDeviceCount(nonCompliantFeature, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a feature non-compliant " +
"device count over the total. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a feature non-compliant device count over the total.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> featureNonCompliantDeviceCountDataWrapper = new LinkedHashMap<>();
featureNonCompliantDeviceCountDataWrapper.put("group", "filtered");
featureNonCompliantDeviceCountDataWrapper.put("label", "filtered");
featureNonCompliantDeviceCountDataWrapper.put("count", featureNonCompliantDeviceCount);
// creating TotalDeviceCount Data Wrapper
int totalDeviceCount;
try {
totalDeviceCount = gadgetDataService.getTotalDeviceCount();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve the total device count over filtered feature non-compliant.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> totalDeviceCountDataWrapper = new LinkedHashMap<>();
totalDeviceCountDataWrapper.put("group", "total");
totalDeviceCountDataWrapper.put("label", "Total");
totalDeviceCountDataWrapper.put("count", totalDeviceCount);
List<Map<String, Object>> featureNonCompliantDeviceCountOverTotalDataWrapper = new ArrayList<>();
featureNonCompliantDeviceCountOverTotalDataWrapper.add(featureNonCompliantDeviceCountDataWrapper);
featureNonCompliantDeviceCountOverTotalDataWrapper.add(totalDeviceCountDataWrapper);
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("feature-non-compliant-device-count-over-total");
dashboardGadgetDataWrapper.setData(featureNonCompliantDeviceCountOverTotalDataWrapper);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
@GET
@Path("filtered-devices-with-details")
public Response getFilteredDevicesWithDetails(@QueryParam("connectivity-status") String connectivityStatus,
@QueryParam("potential-vulnerability") String potentialVulnerability,
@QueryParam("platform") String platform,
@QueryParam("ownership") String ownership,
@QueryParam("pagination-enabled") String paginationEnabled,
@QueryParam("start-index") int startIndex,
@QueryParam("result-count") int resultCount) throws MDMAPIException {
if (paginationEnabled == null) {
Message message = new Message();
message.setErrorMessage("Missing required query parameter.");
message.setDescription("Pagination-enabled query parameter with value true or false is required.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} else if ("true".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getDevicesWithDetails(filterSet, startIndex, resultCount);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of " +
"devices with details. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> deviceDetailEntryDataWrapper;
List<Map<String, Object>> deviceDetailEntriesDataWrapper = new ArrayList<>();
for (Object listElement : paginationResult.getData()) {
Map entry = (Map<?, ?>) listElement;
deviceDetailEntryDataWrapper = new LinkedHashMap<>();
deviceDetailEntryDataWrapper.put("device-id", entry.get("device-id"));
deviceDetailEntryDataWrapper.put("platform", entry.get("platform"));
deviceDetailEntryDataWrapper.put("ownership", entry.get("ownership"));
deviceDetailEntryDataWrapper.put("connectivity-details", entry.get("connectivity-details"));
deviceDetailEntriesDataWrapper.add(deviceDetailEntryDataWrapper);
}
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
dashboardPaginationGadgetDataWrapper.setContext("filtered-device-details");
dashboardPaginationGadgetDataWrapper.setData(deviceDetailEntriesDataWrapper);
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else if ("false".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setConnectivityStatus(connectivityStatus);
filterSet.setPotentialVulnerability(potentialVulnerability);
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
List<Map<String, Object>> devicesWithDetails;
try {
devicesWithDetails = gadgetDataService.getDevicesWithDetails(filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of " +
"devices with details. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("device-details");
dashboardGadgetDataWrapper.setData(devicesWithDetails);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription("Invalid value for query parameter pagination-enabled. " +
"Should be either true or false.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
}
}
@GET
@Path("feature-non-compliant-devices-with-details")
public Response getFeatureNonCompliantDevicesWithDetails(@QueryParam("non-compliant-feature") String nonCompliantFeature,
@QueryParam("platform") String platform,
@QueryParam("ownership") String ownership,
@QueryParam("pagination-enabled") String paginationEnabled,
@QueryParam("start-index") int startIndex,
@QueryParam("result-count") int resultCount) throws MDMAPIException {
if (paginationEnabled == null) {
Message message = new Message();
message.setErrorMessage("Missing required query parameters.");
message.setDescription("Query parameter pagination-enabled with value true or false is required.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} else if ("true".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
PaginationResult paginationResult;
try {
paginationResult = gadgetDataService.
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeature, filterSet, startIndex, resultCount);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
"devices with details. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
Map<String, Object> featureNonCompliantDeviceDetailEntryDataWrapper;
List<Map<String, Object>> featureNonCompliantDeviceDetailEntriesDataWrapper = new ArrayList<>();
for (Object listElement : paginationResult.getData()) {
Map entry = (Map<?, ?>) listElement;
featureNonCompliantDeviceDetailEntryDataWrapper = new LinkedHashMap<>();
featureNonCompliantDeviceDetailEntryDataWrapper.put("device-id", entry.get("device-id"));
featureNonCompliantDeviceDetailEntryDataWrapper.put("platform", entry.get("platform"));
featureNonCompliantDeviceDetailEntryDataWrapper.put("ownership", entry.get("ownership"));
featureNonCompliantDeviceDetailEntryDataWrapper.put("connectivity-details", entry.get("connectivity-details"));
featureNonCompliantDeviceDetailEntriesDataWrapper.add(featureNonCompliantDeviceDetailEntryDataWrapper);
}
DashboardPaginationGadgetDataWrapper
dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
dashboardPaginationGadgetDataWrapper.setContext("feature-non-compliant-device-details");
dashboardPaginationGadgetDataWrapper.setData(featureNonCompliantDeviceDetailEntriesDataWrapper);
dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardPaginationGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else if ("false".equals(paginationEnabled)) {
// getting gadget data service
GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
// constructing filter set
FilterSet filterSet = new FilterSet();
filterSet.setPlatform(platform);
filterSet.setOwnership(ownership);
List<Map<String, Object>> featureNonCompliantDevicesWithDetails;
try {
featureNonCompliantDevicesWithDetails = gadgetDataService.
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeature, filterSet);
} catch (InvalidParameterValueException e) {
log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
Message message = new Message();
message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
message.setDescription("This was while trying to execute relevant service layer function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
"devices with details. " + e.getErrorMessage());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
} catch (SQLException e) {
String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
"@ Dashboard API layer to retrieve a filtered set of feature non-compliant set of devices with details.";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
dashboardGadgetDataWrapper.setContext("feature-non-compliant-device-details");
dashboardGadgetDataWrapper.setData(featureNonCompliantDevicesWithDetails);
List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
responsePayload.add(dashboardGadgetDataWrapper);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
Message message = new Message();
message.setErrorMessage("Invalid query parameter value.");
message.setDescription("Invalid value for " +
"query parameter pagination-enabled. Should be either true or false.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
}
}
}
|
Adding temporary development code bits for dashboard apis
|
modules/apps/jax-rs/mdm-admin/src/main/java/org/wso2/carbon/mdm/api/Dashboard.java
|
Adding temporary development code bits for dashboard apis
|
<ide><path>odules/apps/jax-rs/mdm-admin/src/main/java/org/wso2/carbon/mdm/api/Dashboard.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
<add>import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DetailedDeviceEntry;
<add>import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DeviceCountByGroupEntry;
<ide> import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
<ide> import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
<ide> import org.wso2.carbon.device.mgt.common.PaginationResult;
<ide> import org.wso2.carbon.mdm.exception.Message;
<ide>
<ide> import javax.ws.rs.*;
<del>import javax.ws.rs.core.Context;
<ide> import javax.ws.rs.core.Response;
<del>import javax.ws.rs.core.UriInfo;
<ide> import java.sql.SQLException;
<ide> import java.util.ArrayList;
<del>import java.util.LinkedHashMap;
<ide> import java.util.List;
<del>import java.util.Map;
<ide>
<ide> @Produces({"application/json"})
<ide> @Consumes({"application/json"})
<ide>
<ide> private static Log log = LogFactory.getLog(Dashboard.class);
<ide>
<del> @GET
<del> @Path("overview-of-devices")
<add> // Constants related to Dashboard filtering
<add> public static final String CONNECTIVITY_STATUS = "connectivity-status";
<add> public static final String POTENTIAL_VULNERABILITY = "potential-vulnerability";
<add> public static final String NON_COMPLIANT_FEATURE_CODE = "non-compliant-feature-code";
<add> public static final String PLATFORM = "platform";
<add> public static final String OWNERSHIP_TYPE = "ownership";
<add> // Constants related to pagination
<add> public static final String PAGINATION_ENABLED = "pagination-enabled";
<add> public static final String START_INDEX = "start-index";
<add> public static final String RESULT_COUNT = "result-count";
<add>
<add> @GET
<add> @Path("device-count-overview")
<ide> public Response getOverviewDeviceCounts() throws MDMAPIException {
<ide> GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
<ide>
<ide> // creating TotalDeviceCount Data Wrapper
<del> int totalDeviceCount;
<add> DeviceCountByGroupEntry totalDeviceCount;
<ide> try {
<ide> totalDeviceCount = gadgetDataService.getTotalDeviceCount();
<ide> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve total device count.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> totalDeviceCountDataWrapper = new LinkedHashMap<>();
<del> totalDeviceCountDataWrapper.put("group", "total");
<del> totalDeviceCountDataWrapper.put("label", "Total");
<del> totalDeviceCountDataWrapper.put("count", totalDeviceCount);
<del>
<del> // creating ActiveDeviceCount Data Wrapper
<del> int activeDeviceCount;
<del> try {
<del> activeDeviceCount = gadgetDataService.getActiveDeviceCount();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<del> "@ Dashboard API layer to retrieve active device count.";
<del> log.error(msg, e);
<del> throw new MDMAPIException(msg, e);
<del> }
<del>
<del> Map<String, Object> activeDeviceCountDataWrapper = new LinkedHashMap<>();
<del> activeDeviceCountDataWrapper.put("group", "active");
<del> activeDeviceCountDataWrapper.put("label", "Active");
<del> activeDeviceCountDataWrapper.put("count", activeDeviceCount);
<del>
<del> // creating inactiveDeviceCount Data Wrapper
<del> int inactiveDeviceCount;
<del> try {
<del> inactiveDeviceCount = gadgetDataService.getInactiveDeviceCount();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<del> "@ Dashboard API layer to retrieve inactive device count.";
<del> log.error(msg, e);
<del> throw new MDMAPIException(msg, e);
<del> }
<del>
<del> Map<String, Object> inactiveDeviceCountDataWrapper = new LinkedHashMap<>();
<del> inactiveDeviceCountDataWrapper.put("group", "inactive");
<del> inactiveDeviceCountDataWrapper.put("label", "Inactive");
<del> inactiveDeviceCountDataWrapper.put("count", inactiveDeviceCount);
<del>
<del> // creating removedDeviceCount Data Wrapper
<del> int removedDeviceCount;
<del> try {
<del> removedDeviceCount = gadgetDataService.getRemovedDeviceCount();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<del> "@ Dashboard API layer to retrieve removed device count.";
<del> log.error(msg, e);
<del> throw new MDMAPIException(msg, e);
<del> }
<del>
<del> Map<String, Object> removedDeviceCountDataWrapper = new LinkedHashMap<>();
<del> removedDeviceCountDataWrapper.put("group", "removed");
<del> removedDeviceCountDataWrapper.put("label", "Removed");
<del> removedDeviceCountDataWrapper.put("count", removedDeviceCount);
<del>
<del> List<Map<String, Object>> overviewDeviceCountsDataWrapper = new ArrayList<>();
<del> overviewDeviceCountsDataWrapper.add(totalDeviceCountDataWrapper);
<del> overviewDeviceCountsDataWrapper.add(activeDeviceCountDataWrapper);
<del> overviewDeviceCountsDataWrapper.add(inactiveDeviceCountDataWrapper);
<del> overviewDeviceCountsDataWrapper.add(removedDeviceCountDataWrapper);
<del>
<del> dashboardGadgetDataWrapper.setContext("connectivity-status");
<add> List<Object> overviewDeviceCountsDataWrapper = new ArrayList<>();
<add> overviewDeviceCountsDataWrapper.add(totalDeviceCount);
<add>
<add> List<DeviceCountByGroupEntry> deviceCountsByConnectivityStatuses;
<add> try {
<add> deviceCountsByConnectivityStatuses = gadgetDataService.getDeviceCountsByConnectivityStatuses();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<add> "@ Dashboard API layer to retrieve device counts by connectivity statuses.";
<add> log.error(msg, e);
<add> throw new MDMAPIException(msg, e);
<add> }
<add>
<add> for (DeviceCountByGroupEntry entry : deviceCountsByConnectivityStatuses) {
<add> overviewDeviceCountsDataWrapper.add(entry);
<add> }
<add>
<add> dashboardGadgetDataWrapper.setContext("Overview-of-device-counts");
<add> dashboardGadgetDataWrapper.setFilteringAttribute(CONNECTIVITY_STATUS);
<ide> dashboardGadgetDataWrapper.setData(overviewDeviceCountsDataWrapper);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> }
<ide>
<ide> @GET
<del> @Path("potential-vulnerabilities")
<del> public Response getVulnerableDeviceCounts() throws MDMAPIException {
<add> @Path("device-counts-by-potential-vulnerabilities")
<add> public Response getDeviceCountsByPotentialVulnerabilities() throws MDMAPIException {
<ide> GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
<add>
<add> List<DeviceCountByGroupEntry> deviceCountsByPotentialVulnerabilities;
<add> try {
<add> deviceCountsByPotentialVulnerabilities = gadgetDataService.getDeviceCountsByPotentialVulnerabilities();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<add> "@ Dashboard API layer to retrieve device counts by potential vulnerabilities.";
<add> log.error(msg, e);
<add> throw new MDMAPIException(msg, e);
<add> }
<add>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
<del>
<del> // creating non-compliant Data Wrapper
<del> int nonCompliantDeviceCount;
<del> try {
<del> nonCompliantDeviceCount = gadgetDataService.getNonCompliantDeviceCount();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<del> "@ Dashboard API layer to retrieve non-compliant device count.";
<del> log.error(msg, e);
<del> throw new MDMAPIException(msg, e);
<del> }
<del>
<del> Map<String, Object> nonCompliantDeviceCountDataWrapper = new LinkedHashMap<>();
<del> nonCompliantDeviceCountDataWrapper.put("group", "non-compliant");
<del> nonCompliantDeviceCountDataWrapper.put("label", "Non-Compliant");
<del> nonCompliantDeviceCountDataWrapper.put("count", nonCompliantDeviceCount);
<del>
<del> // creating unmonitoredDeviceCount Data Wrapper
<del> int unmonitoredDeviceCount;
<del> try {
<del> unmonitoredDeviceCount = gadgetDataService.getUnmonitoredDeviceCount();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<del> "@ Dashboard API layer to retrieve unmonitored device count.";
<del> log.error(msg, e);
<del> throw new MDMAPIException(msg, e);
<del> }
<del>
<del> Map<String, Object> unmonitoredDeviceCountDataWrapper = new LinkedHashMap<>();
<del> unmonitoredDeviceCountDataWrapper.put("group", "unmonitored");
<del> unmonitoredDeviceCountDataWrapper.put("label", "Unmonitored");
<del> unmonitoredDeviceCountDataWrapper.put("count", unmonitoredDeviceCount);
<del>
<del> List<Map<String, Object>> vulnerableDeviceCountsDataWrapper = new ArrayList<>();
<del> vulnerableDeviceCountsDataWrapper.add(nonCompliantDeviceCountDataWrapper);
<del> vulnerableDeviceCountsDataWrapper.add(unmonitoredDeviceCountDataWrapper);
<del>
<del> dashboardGadgetDataWrapper.setContext("potential-vulnerability");
<del> dashboardGadgetDataWrapper.setData(vulnerableDeviceCountsDataWrapper);
<add> dashboardGadgetDataWrapper.setContext("Device-counts-by-potential-vulnerabilities");
<add> dashboardGadgetDataWrapper.setFilteringAttribute(POTENTIAL_VULNERABILITY);
<add> dashboardGadgetDataWrapper.setData(deviceCountsByPotentialVulnerabilities);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> responsePayload.add(dashboardGadgetDataWrapper);
<ide> }
<ide>
<ide> @GET
<del> @Path("non-compliant-by-feature")
<del> public Response getNonCompliantDeviceCountsByFeatures(@QueryParam("start-index") int startIndex,
<del> @QueryParam("result-count") int resultCount, @Context UriInfo uriInfo) throws MDMAPIException {
<add> @Path("non-compliant-device-counts-by-features")
<add> public Response getNonCompliantDeviceCountsByFeatures(@QueryParam(START_INDEX) int startIndex,
<add> @QueryParam(RESULT_COUNT) int resultCount) throws MDMAPIException {
<ide>
<ide> GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
<ide> DashboardPaginationGadgetDataWrapper
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a non-compliant set of device counts by features. " + e.getErrorMessage());
<del> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a non-compliant set of device counts by features.");
<add> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a non-compliant set of device counts by features.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> nonCompliantDeviceCountByFeatureDataWrapper;
<del> List<Map<String, Object>> nonCompliantDeviceCountsByFeaturesDataWrapper = new ArrayList<>();
<del> for (Object listElement : paginationResult.getData()) {
<del> Map entry = (Map<?, ?>) listElement;
<del> nonCompliantDeviceCountByFeatureDataWrapper = new LinkedHashMap<>();
<del> nonCompliantDeviceCountByFeatureDataWrapper.put("group", entry.get("FEATURE_CODE"));
<del> nonCompliantDeviceCountByFeatureDataWrapper.put("label", entry.get("FEATURE_CODE"));
<del> nonCompliantDeviceCountByFeatureDataWrapper.put("count", entry.get("DEVICE_COUNT"));
<del> nonCompliantDeviceCountsByFeaturesDataWrapper.add(nonCompliantDeviceCountByFeatureDataWrapper);
<del> }
<del>
<del> dashboardPaginationGadgetDataWrapper.setContext("non-compliant-feature");
<del> dashboardPaginationGadgetDataWrapper.setData(nonCompliantDeviceCountsByFeaturesDataWrapper);
<add> dashboardPaginationGadgetDataWrapper.setContext("Non-compliant-device-counts-by-feature");
<add> dashboardPaginationGadgetDataWrapper.setFilteringAttribute(NON_COMPLIANT_FEATURE_CODE);
<add> dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
<ide> dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
<ide>
<ide> List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> }
<ide>
<ide> @GET
<del> @Path("device-groupings")
<del> public Response getDeviceGroupingCounts(@QueryParam("connectivity-status") String connectivityStatus,
<del> @QueryParam("potential-vulnerability") String potentialVulnerability,
<del> @QueryParam("platform") String platform,
<del> @QueryParam("ownership") String ownership) throws MDMAPIException {
<add> @Path("device-counts-by-groups")
<add> public Response getDeviceCountsByGroups(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
<add> @QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
<add> @QueryParam(PLATFORM) String platform,
<add> @QueryParam(OWNERSHIP_TYPE) String ownership) throws MDMAPIException {
<ide>
<ide> // getting gadget data service
<ide> GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
<ide> filterSet.setOwnership(ownership);
<ide>
<ide> // creating device-Counts-by-platforms Data Wrapper
<del> Map<String, Integer> deviceCountsByPlatforms;
<add> List<DeviceCountByGroupEntry> deviceCountsByPlatforms;
<ide> try {
<ide> deviceCountsByPlatforms = gadgetDataService.getDeviceCountsByPlatforms(filterSet);
<ide> } catch (InvalidParameterValueException e) {
<del> log.error("Error occurred @ Gadget Data Service layer due to invalid parameters.", e);
<del> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of device counts by platforms. " + e.getErrorMessage());
<del> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<add> Message message = new Message();
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered set of device counts by platforms.");
<add> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered set of device counts by platforms.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> deviceCountByPlatformDataWrapper;
<del> List<Map<String, Object>> deviceCountsByPlatformsDataWrapper = new ArrayList<>();
<del> for (Map.Entry<String, Integer> entry : deviceCountsByPlatforms.entrySet()) {
<del> deviceCountByPlatformDataWrapper = new LinkedHashMap<>();
<del> deviceCountByPlatformDataWrapper.put("group", entry.getKey());
<del> deviceCountByPlatformDataWrapper.put("label", entry.getKey());
<del> deviceCountByPlatformDataWrapper.put("count", entry.getValue());
<del> deviceCountsByPlatformsDataWrapper.add(deviceCountByPlatformDataWrapper);
<del> }
<del>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper1.setContext("platform");
<del> dashboardGadgetDataWrapper1.setData(deviceCountsByPlatformsDataWrapper);
<add> dashboardGadgetDataWrapper1.setContext("Device-counts-by-platforms");
<add> dashboardGadgetDataWrapper1.setFilteringAttribute(PLATFORM);
<add> dashboardGadgetDataWrapper1.setData(deviceCountsByPlatforms);
<ide>
<ide> // creating device-Counts-by-ownership-types Data Wrapper
<del> Map<String, Integer> deviceCountsByOwnershipTypes;
<add> List<DeviceCountByGroupEntry> deviceCountsByOwnershipTypes;
<ide> try {
<ide> deviceCountsByOwnershipTypes = gadgetDataService.getDeviceCountsByOwnershipTypes(filterSet);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of device " +
<del> "counts by ownership types. " + e.getErrorMessage());
<del> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered set of device counts by ownership types.");
<add> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered set of device counts by ownership types.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> deviceCountByOwnershipTypeDataWrapper;
<del> List<Map<String, Object>> deviceCountsByOwnershipTypesDataWrapper = new ArrayList<>();
<del> for (Map.Entry<String, Integer> entry : deviceCountsByOwnershipTypes.entrySet()) {
<del> deviceCountByOwnershipTypeDataWrapper = new LinkedHashMap<>();
<del> deviceCountByOwnershipTypeDataWrapper.put("group", entry.getKey());
<del> deviceCountByOwnershipTypeDataWrapper.put("label", entry.getKey());
<del> deviceCountByOwnershipTypeDataWrapper.put("count", entry.getValue());
<del> deviceCountsByOwnershipTypesDataWrapper.add(deviceCountByOwnershipTypeDataWrapper);
<del> }
<del>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper2.setContext("ownership");
<del> dashboardGadgetDataWrapper2.setData(deviceCountsByOwnershipTypesDataWrapper);
<add> dashboardGadgetDataWrapper2.setContext("Device-counts-by-ownership-type");
<add> dashboardGadgetDataWrapper2.setFilteringAttribute(OWNERSHIP_TYPE);
<add> dashboardGadgetDataWrapper2.setData(deviceCountsByOwnershipTypes);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> responsePayload.add(dashboardGadgetDataWrapper1);
<ide> }
<ide>
<ide> @GET
<del> @Path("feature-non-compliant-device-groupings")
<del> public Response getFeatureNonCompliantDeviceGroupingCounts(@QueryParam("non-compliant-feature") String nonCompliantFeature,
<del> @QueryParam("platform") String platform,
<del> @QueryParam("ownership") String ownership)
<add> @Path("feature-non-compliant-device-counts-by-groups")
<add> public Response getFeatureNonCompliantDeviceCountsByGroups(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
<add> @QueryParam(PLATFORM) String platform,
<add> @QueryParam(OWNERSHIP_TYPE) String ownership)
<ide> throws MDMAPIException {
<ide> // getting gadget data service
<ide> GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
<ide> filterSet.setOwnership(ownership);
<ide>
<ide> // creating feature-non-compliant-device-Counts-by-platforms Data Wrapper
<del> Map<String, Integer> featureNonCompliantDeviceCountsByPlatforms;
<add> List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByPlatforms;
<ide> try {
<ide> featureNonCompliantDeviceCountsByPlatforms = gadgetDataService.
<del> getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeature, filterSet);
<add> getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filterSet);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant device " +
<del> "counts by platforms. " + e.getErrorMessage());
<del> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered set of " +
<add> "feature non-compliant device counts by platforms.");
<add> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant device counts by platforms.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> featureNonCompliantDeviceCountByPlatformDataWrapper;
<del> List<Map<String, Object>> featureNonCompliantDeviceCountsByPlatformsDataWrapper = new ArrayList<>();
<del> for (Map.Entry<String, Integer> entry : featureNonCompliantDeviceCountsByPlatforms.entrySet()) {
<del> featureNonCompliantDeviceCountByPlatformDataWrapper = new LinkedHashMap<>();
<del> featureNonCompliantDeviceCountByPlatformDataWrapper.put("group", entry.getKey());
<del> featureNonCompliantDeviceCountByPlatformDataWrapper.put("label", entry.getKey());
<del> featureNonCompliantDeviceCountByPlatformDataWrapper.put("count", entry.getValue());
<del> featureNonCompliantDeviceCountsByPlatformsDataWrapper.
<del> add(featureNonCompliantDeviceCountByPlatformDataWrapper);
<del> }
<del>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper1 = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper1.setContext("platform");
<del> dashboardGadgetDataWrapper1.setData(featureNonCompliantDeviceCountsByPlatformsDataWrapper);
<add> dashboardGadgetDataWrapper1.setContext("Feature-non-compliant-device-counts-by-platforms");
<add> dashboardGadgetDataWrapper1.setFilteringAttribute(PLATFORM);
<add> dashboardGadgetDataWrapper1.setData(featureNonCompliantDeviceCountsByPlatforms);
<ide>
<ide> // creating feature-non-compliant-device-Counts-by-ownership-types Data Wrapper
<del> Map<String, Integer> featureNonCompliantDeviceCountsByOwnershipTypes;
<add> List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByOwnershipTypes;
<ide> try {
<ide> featureNonCompliantDeviceCountsByOwnershipTypes = gadgetDataService.
<del> getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeature, filterSet);
<add> getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filterSet);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant device " +
<del> "counts by ownership types. " + e.getErrorMessage());
<del> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + "This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered set of " +
<add> "feature non-compliant device counts by ownership types.");
<add> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
<ide> "device counts by ownership types.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> featureNonCompliantDeviceCountByOwnershipTypeDataWrapper;
<del> List<Map<String, Object>> featureNonCompliantDeviceCountsByOwnershipTypesDataWrapper = new ArrayList<>();
<del> for (Map.Entry<String, Integer> entry : featureNonCompliantDeviceCountsByOwnershipTypes.entrySet()) {
<del> featureNonCompliantDeviceCountByOwnershipTypeDataWrapper = new LinkedHashMap<>();
<del> featureNonCompliantDeviceCountByOwnershipTypeDataWrapper.put("group", entry.getKey());
<del> featureNonCompliantDeviceCountByOwnershipTypeDataWrapper.put("label", entry.getKey());
<del> featureNonCompliantDeviceCountByOwnershipTypeDataWrapper.put("count", entry.getValue());
<del> featureNonCompliantDeviceCountsByOwnershipTypesDataWrapper.
<del> add(featureNonCompliantDeviceCountByOwnershipTypeDataWrapper);
<del> }
<del>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper2 = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper2.setContext("ownership");
<del> dashboardGadgetDataWrapper2.setData(featureNonCompliantDeviceCountsByOwnershipTypesDataWrapper);
<add> dashboardGadgetDataWrapper2.setContext("Feature-non-compliant-device-counts-by-ownership-types");
<add> dashboardGadgetDataWrapper2.setFilteringAttribute(OWNERSHIP_TYPE);
<add> dashboardGadgetDataWrapper2.setData(featureNonCompliantDeviceCountsByOwnershipTypes);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> responsePayload.add(dashboardGadgetDataWrapper1);
<ide> }
<ide>
<ide> @GET
<del> @Path("filtered-devices-over-total")
<del> public Response getFilteredDeviceCountOverTotal(@QueryParam("connectivity-status") String connectivityStatus,
<del> @QueryParam("potential-vulnerability") String potentialVulnerability,
<del> @QueryParam("platform") String platform,
<del> @QueryParam("ownership") String ownership) throws MDMAPIException {
<add> @Path("filtered-device-count-over-total")
<add> public Response getFilteredDeviceCountOverTotal(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
<add> @QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
<add> @QueryParam(PLATFORM) String platform,
<add> @QueryParam(OWNERSHIP_TYPE) String ownership)
<add> throws MDMAPIException {
<ide>
<ide> // getting gadget data service
<ide> GadgetDataService gadgetDataService = MDMAPIUtils.getGadgetDataService();
<ide> filterSet.setOwnership(ownership);
<ide>
<ide> // creating filteredDeviceCount Data Wrapper
<del> int filteredDeviceCount;
<add> DeviceCountByGroupEntry filteredDeviceCount;
<ide> try {
<ide> filteredDeviceCount = gadgetDataService.getDeviceCount(filterSet);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered device count over the total. " + e.getErrorMessage());
<del> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered device count over the total.");
<add> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered device count over the total.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> filteredDeviceCountDataWrapper = new LinkedHashMap<>();
<del> filteredDeviceCountDataWrapper.put("group", "filtered");
<del> filteredDeviceCountDataWrapper.put("label", "filtered");
<del> filteredDeviceCountDataWrapper.put("count", filteredDeviceCount);
<del>
<ide> // creating TotalDeviceCount Data Wrapper
<del> int totalDeviceCount;
<add> DeviceCountByGroupEntry totalDeviceCount;
<ide> try {
<ide> totalDeviceCount = gadgetDataService.getTotalDeviceCount();
<ide> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve the total device count over filtered.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> totalDeviceCountDataWrapper = new LinkedHashMap<>();
<del> totalDeviceCountDataWrapper.put("group", "total");
<del> totalDeviceCountDataWrapper.put("label", "Total");
<del> totalDeviceCountDataWrapper.put("count", totalDeviceCount);
<del>
<del> List<Map<String, Object>> filteredDeviceCountOverTotalDataWrapper = new ArrayList<>();
<del> filteredDeviceCountOverTotalDataWrapper.add(filteredDeviceCountDataWrapper);
<del> filteredDeviceCountOverTotalDataWrapper.add(totalDeviceCountDataWrapper);
<add> List<Object> filteredDeviceCountOverTotalDataWrapper = new ArrayList<>();
<add> filteredDeviceCountOverTotalDataWrapper.add(filteredDeviceCount);
<add> filteredDeviceCountOverTotalDataWrapper.add(totalDeviceCount);
<ide>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper.setContext("filtered-device-count-over-total");
<add> dashboardGadgetDataWrapper.setContext("Filtered-device-count-over-total");
<add> dashboardGadgetDataWrapper.setFilteringAttribute(null);
<ide> dashboardGadgetDataWrapper.setData(filteredDeviceCountOverTotalDataWrapper);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> }
<ide>
<ide> @GET
<del> @Path("feature-non-compliant-devices-over-total")
<del> public Response getFeatureNonCompliantDeviceCountOverTotal(@QueryParam("non-compliant-feature") String nonCompliantFeature,
<del> @QueryParam("platform") String platform,
<del> @QueryParam("ownership") String ownership)
<add> @Path("feature-non-compliant-device-count-over-total")
<add> public Response getFeatureNonCompliantDeviceCountOverTotal(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
<add> @QueryParam(PLATFORM) String platform,
<add> @QueryParam(OWNERSHIP_TYPE) String ownership)
<ide> throws MDMAPIException {
<ide>
<ide> // getting gadget data service
<ide> filterSet.setOwnership(ownership);
<ide>
<ide> // creating featureNonCompliantDeviceCount Data Wrapper
<del> int featureNonCompliantDeviceCount;
<add> DeviceCountByGroupEntry featureNonCompliantDeviceCount;
<ide> try {
<ide> featureNonCompliantDeviceCount = gadgetDataService.
<del> getFeatureNonCompliantDeviceCount(nonCompliantFeature, filterSet);
<add> getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filterSet);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a feature non-compliant " +
<del> "device count over the total. " + e.getErrorMessage());
<del> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<del> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a feature non-compliant device count over the total.");
<add> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<add> } catch (SQLException e) {
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a feature non-compliant device count over the total.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> featureNonCompliantDeviceCountDataWrapper = new LinkedHashMap<>();
<del> featureNonCompliantDeviceCountDataWrapper.put("group", "filtered");
<del> featureNonCompliantDeviceCountDataWrapper.put("label", "filtered");
<del> featureNonCompliantDeviceCountDataWrapper.put("count", featureNonCompliantDeviceCount);
<del>
<ide> // creating TotalDeviceCount Data Wrapper
<del> int totalDeviceCount;
<add> DeviceCountByGroupEntry totalDeviceCount;
<ide> try {
<ide> totalDeviceCount = gadgetDataService.getTotalDeviceCount();
<ide> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve the total device count over filtered feature non-compliant.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> totalDeviceCountDataWrapper = new LinkedHashMap<>();
<del> totalDeviceCountDataWrapper.put("group", "total");
<del> totalDeviceCountDataWrapper.put("label", "Total");
<del> totalDeviceCountDataWrapper.put("count", totalDeviceCount);
<del>
<del> List<Map<String, Object>> featureNonCompliantDeviceCountOverTotalDataWrapper = new ArrayList<>();
<del> featureNonCompliantDeviceCountOverTotalDataWrapper.add(featureNonCompliantDeviceCountDataWrapper);
<del> featureNonCompliantDeviceCountOverTotalDataWrapper.add(totalDeviceCountDataWrapper);
<add> List<Object> featureNonCompliantDeviceCountOverTotalDataWrapper = new ArrayList<>();
<add> featureNonCompliantDeviceCountOverTotalDataWrapper.add(featureNonCompliantDeviceCount);
<add> featureNonCompliantDeviceCountOverTotalDataWrapper.add(totalDeviceCount);
<ide>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper.setContext("feature-non-compliant-device-count-over-total");
<add> dashboardGadgetDataWrapper.setContext("Feature-non-compliant-device-count-over-total");
<add> dashboardGadgetDataWrapper.setFilteringAttribute(null);
<ide> dashboardGadgetDataWrapper.setData(featureNonCompliantDeviceCountOverTotalDataWrapper);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> }
<ide>
<ide> @GET
<del> @Path("filtered-devices-with-details")
<del> public Response getFilteredDevicesWithDetails(@QueryParam("connectivity-status") String connectivityStatus,
<del> @QueryParam("potential-vulnerability") String potentialVulnerability,
<del> @QueryParam("platform") String platform,
<del> @QueryParam("ownership") String ownership,
<del> @QueryParam("pagination-enabled") String paginationEnabled,
<del> @QueryParam("start-index") int startIndex,
<del> @QueryParam("result-count") int resultCount) throws MDMAPIException {
<add> @Path("devices-with-details")
<add> public Response getDevicesWithDetails(@QueryParam(CONNECTIVITY_STATUS) String connectivityStatus,
<add> @QueryParam(POTENTIAL_VULNERABILITY) String potentialVulnerability,
<add> @QueryParam(PLATFORM) String platform,
<add> @QueryParam(OWNERSHIP_TYPE) String ownership,
<add> @QueryParam(PAGINATION_ENABLED) String paginationEnabled,
<add> @QueryParam(START_INDEX) int startIndex,
<add> @QueryParam(RESULT_COUNT) int resultCount) throws MDMAPIException {
<ide>
<ide> if (paginationEnabled == null) {
<ide>
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of " +
<del> "devices with details. " + e.getErrorMessage());
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + "This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered set of devices with details.");
<ide> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<ide> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered set of devices with details.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> deviceDetailEntryDataWrapper;
<del> List<Map<String, Object>> deviceDetailEntriesDataWrapper = new ArrayList<>();
<del> for (Object listElement : paginationResult.getData()) {
<del> Map entry = (Map<?, ?>) listElement;
<del> deviceDetailEntryDataWrapper = new LinkedHashMap<>();
<del> deviceDetailEntryDataWrapper.put("device-id", entry.get("device-id"));
<del> deviceDetailEntryDataWrapper.put("platform", entry.get("platform"));
<del> deviceDetailEntryDataWrapper.put("ownership", entry.get("ownership"));
<del> deviceDetailEntryDataWrapper.put("connectivity-details", entry.get("connectivity-details"));
<del> deviceDetailEntriesDataWrapper.add(deviceDetailEntryDataWrapper);
<del> }
<del>
<ide> DashboardPaginationGadgetDataWrapper
<ide> dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
<del> dashboardPaginationGadgetDataWrapper.setContext("filtered-device-details");
<del> dashboardPaginationGadgetDataWrapper.setData(deviceDetailEntriesDataWrapper);
<add> dashboardPaginationGadgetDataWrapper.setContext("Filtered-and-paginated-devices-with-details");
<add> dashboardPaginationGadgetDataWrapper.setFilteringAttribute(null);
<add> dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
<ide> dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
<ide>
<ide> List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> filterSet.setPlatform(platform);
<ide> filterSet.setOwnership(ownership);
<ide>
<del> List<Map<String, Object>> devicesWithDetails;
<add> List<DetailedDeviceEntry> devicesWithDetails;
<ide> try {
<ide> devicesWithDetails = gadgetDataService.getDevicesWithDetails(filterSet);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of " +
<del> "devices with details. " + e.getErrorMessage());
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered set of devices with details.");
<ide> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<ide> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered set of devices with details.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper.setContext("device-details");
<add> dashboardGadgetDataWrapper.setContext("filtered-devices-with-details");
<add> dashboardGadgetDataWrapper.setFilteringAttribute(null);
<ide> dashboardGadgetDataWrapper.setData(devicesWithDetails);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide>
<ide> @GET
<ide> @Path("feature-non-compliant-devices-with-details")
<del> public Response getFeatureNonCompliantDevicesWithDetails(@QueryParam("non-compliant-feature") String nonCompliantFeature,
<del> @QueryParam("platform") String platform,
<del> @QueryParam("ownership") String ownership,
<del> @QueryParam("pagination-enabled") String paginationEnabled,
<del> @QueryParam("start-index") int startIndex,
<del> @QueryParam("result-count") int resultCount) throws MDMAPIException {
<del>
<add> public Response getFeatureNonCompliantDevicesWithDetails(@QueryParam(NON_COMPLIANT_FEATURE_CODE) String nonCompliantFeatureCode,
<add> @QueryParam(PLATFORM) String platform,
<add> @QueryParam(OWNERSHIP_TYPE) String ownership,
<add> @QueryParam(PAGINATION_ENABLED) String paginationEnabled,
<add> @QueryParam(START_INDEX) int startIndex,
<add> @QueryParam(RESULT_COUNT) int resultCount)
<add> throws MDMAPIException {
<ide> if (paginationEnabled == null) {
<ide>
<ide> Message message = new Message();
<ide> PaginationResult paginationResult;
<ide> try {
<ide> paginationResult = gadgetDataService.
<del> getFeatureNonCompliantDevicesWithDetails(nonCompliantFeature, filterSet, startIndex, resultCount);
<add> getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet, startIndex, resultCount);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
<del> "devices with details. " + e.getErrorMessage());
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + " This was while trying to execute relevant service layer " +
<add> "function @ Dashboard API layer to retrieve a filtered set of " +
<add> "feature non-compliant devices with details.");
<ide> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<ide> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<ide> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant devices with details.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<del> Map<String, Object> featureNonCompliantDeviceDetailEntryDataWrapper;
<del> List<Map<String, Object>> featureNonCompliantDeviceDetailEntriesDataWrapper = new ArrayList<>();
<del> for (Object listElement : paginationResult.getData()) {
<del> Map entry = (Map<?, ?>) listElement;
<del> featureNonCompliantDeviceDetailEntryDataWrapper = new LinkedHashMap<>();
<del> featureNonCompliantDeviceDetailEntryDataWrapper.put("device-id", entry.get("device-id"));
<del> featureNonCompliantDeviceDetailEntryDataWrapper.put("platform", entry.get("platform"));
<del> featureNonCompliantDeviceDetailEntryDataWrapper.put("ownership", entry.get("ownership"));
<del> featureNonCompliantDeviceDetailEntryDataWrapper.put("connectivity-details", entry.get("connectivity-details"));
<del> featureNonCompliantDeviceDetailEntriesDataWrapper.add(featureNonCompliantDeviceDetailEntryDataWrapper);
<del> }
<del>
<ide> DashboardPaginationGadgetDataWrapper
<ide> dashboardPaginationGadgetDataWrapper = new DashboardPaginationGadgetDataWrapper();
<del> dashboardPaginationGadgetDataWrapper.setContext("feature-non-compliant-device-details");
<del> dashboardPaginationGadgetDataWrapper.setData(featureNonCompliantDeviceDetailEntriesDataWrapper);
<add> dashboardPaginationGadgetDataWrapper.setContext("Paginated-feature-non-compliant-devices-with-details");
<add> dashboardPaginationGadgetDataWrapper.setFilteringAttribute(null);
<add> dashboardPaginationGadgetDataWrapper.setData(paginationResult.getData());
<ide> dashboardPaginationGadgetDataWrapper.setTotalRecordCount(paginationResult.getRecordsTotal());
<ide>
<ide> List<DashboardPaginationGadgetDataWrapper> responsePayload = new ArrayList<>();
<ide> filterSet.setPlatform(platform);
<ide> filterSet.setOwnership(ownership);
<ide>
<del> List<Map<String, Object>> featureNonCompliantDevicesWithDetails;
<add> List<DetailedDeviceEntry> featureNonCompliantDevicesWithDetails;
<ide> try {
<ide> featureNonCompliantDevicesWithDetails = gadgetDataService.
<del> getFeatureNonCompliantDevicesWithDetails(nonCompliantFeature, filterSet);
<add> getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet);
<ide> } catch (InvalidParameterValueException e) {
<ide> log.error("Error occurred @ Gadget Data Service layer due to invalid parameter value.", e);
<ide> Message message = new Message();
<del> message.setErrorMessage("Error occurred @ Gadget Data Service layer due to invalid parameter value.");
<del> message.setDescription("This was while trying to execute relevant service layer function " +
<del> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant " +
<del> "devices with details. " + e.getErrorMessage());
<add> message.setErrorMessage("Invalid query parameter value.");
<add> message.setDescription(e.getErrorMessage() + "This was while trying to execute relevant data service " +
<add> "function @ Dashboard API layer to retrieve a filtered set of " +
<add> "feature non-compliant devices with details.");
<ide> return Response.status(HttpStatus.SC_BAD_REQUEST).entity(message).build();
<ide> } catch (SQLException e) {
<del> String msg = "SQL error occurred @ Gadget Data Service layer while trying to execute relevant function " +
<del> "@ Dashboard API layer to retrieve a filtered set of feature non-compliant set of devices with details.";
<add> String msg = "An internal error occurred while trying to execute relevant data service function " +
<add> "@ Dashboard API layer to retrieve a filtered set of feature " +
<add> "non-compliant set of devices with details.";
<ide> log.error(msg, e);
<ide> throw new MDMAPIException(msg, e);
<ide> }
<ide>
<ide> DashboardGadgetDataWrapper dashboardGadgetDataWrapper = new DashboardGadgetDataWrapper();
<del> dashboardGadgetDataWrapper.setContext("feature-non-compliant-device-details");
<add> dashboardGadgetDataWrapper.setContext("Feature-non-compliant-devices-with-details");
<add> dashboardGadgetDataWrapper.setFilteringAttribute(null);
<ide> dashboardGadgetDataWrapper.setData(featureNonCompliantDevicesWithDetails);
<ide>
<ide> List<DashboardGadgetDataWrapper> responsePayload = new ArrayList<>();
|
|
Java
|
mit
|
1a939a60685fbf21ebf726642856e4ae01a666e4
| 0 |
simonjenga/takes,xupyprmv/takes,yegor256/takes,xupyprmv/takes,dalifreire/takes,yegor256/takes,dalifreire/takes,simonjenga/takes
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Yegor Bugayenko
*
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.takes.facets.auth.social;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import javax.json.Json;
import org.apache.commons.lang.RandomStringUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.auth.Identity;
import org.takes.facets.fork.FkRegex;
import org.takes.facets.fork.TkFork;
import org.takes.http.FtRemote;
import org.takes.misc.Href;
import org.takes.rq.RqFake;
import org.takes.rq.RqHref;
import org.takes.rq.RqPrint;
import org.takes.rs.RsJson;
/**
* Test case for {@link PsLinkedin}.
* @author Dmitry Zaytsev ([email protected])
* @version $Id$
* @since 0.16
* @checkstyle MagicNumberCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle MultipleStringLiteralsCheck (500 lines)
*/
public final class PsLinkedinTest {
/**
* PsLinkedin can login.
* @throws IOException If some problem inside
*/
@Test
public void logins() throws IOException {
final String code = RandomStringUtils.randomAlphanumeric(10);
final String lapp = RandomStringUtils.randomAlphanumeric(10);
final String lkey = RandomStringUtils.randomAlphanumeric(10);
final String identifier = RandomStringUtils.randomAlphanumeric(10);
final String tokenpattern = "/uas/oauth2/accessToken";
final String peoplepattern = "/v1/people";
final Take take = new TkFork(
new FkRegex(tokenpattern, new TokenTake(code, lapp, lkey)),
new FkRegex(peoplepattern, new PeopleTake(identifier))
);
new FtRemote(take).exec(
new LinkedinScript(code, lapp, lkey, identifier)
);
}
/**
* Take that returns JSON with the authorization token.
* @author Dmitry Zaytsev ([email protected])
* @author Rui Castro ([email protected])
* @version $Id$
* @since 0.33
*/
private final class TokenTake implements Take {
/**
* Request path pattern for token endpoint.
*/
private final String tokenpattern = "/uas/oauth2/accessToken";
/**
* Linkedin authorization code.
*/
private String code;
/**
* Linkedin app.
*/
private String lapp;
/**
* Linkedin key.
*/
private String lkey;
/**
* Ctor.
* @param code Linkedin authorization code.
* @param lapp Linkedin app.
* @param lkey Linkedin key.
*/
TokenTake(final String code, final String lapp, final String lkey) {
this.code = code;
this.lapp = lapp;
this.lkey = lkey;
}
@Override
public Response act(final Request req) throws IOException {
MatcherAssert.assertThat(
new RqPrint(req).printBody(),
Matchers.stringContainsInOrder(
Arrays.asList(
"grant_type=authorization_code",
String.format("client_id=%s", this.lapp),
"redirect_uri=",
String.format("client_secret=%s", this.lkey),
String.format("code=%s", this.code)
)
)
);
MatcherAssert.assertThat(
new RqHref.Base(req).href().toString(),
Matchers.endsWith(this.tokenpattern)
);
return new RsJson(
Json.createObjectBuilder()
.add(
"access_token",
RandomStringUtils.randomAlphanumeric(10)
).build()
);
}
}
/**
* Take that returns JSON with test user data.
* @author Dmitry Zaytsev ([email protected])
* @author Rui Castro ([email protected])
* @version $Id$
* @since 0.33
*/
private final class PeopleTake implements Take {
/**
* Linkedin user identifier.
*/
private String identifier;
/**
* Ctor.
* @param identifier Linkedin user identifier.
*/
PeopleTake(final String identifier) {
this.identifier = identifier;
}
@Override
public Response act(final Request req) throws IOException {
return new RsJson(
Json.createObjectBuilder()
.add("id", this.identifier)
.add("firstname", "Frodo")
.add("lastname", "Baggins")
.build()
);
}
}
/**
* Script to test Linkedin authorization.
* @author Dmitry Zaytsev ([email protected])
* @author Rui Castro ([email protected])
* @version $Id$
* @since 0.33
*/
private final class LinkedinScript implements FtRemote.Script {
/**
* Linkedin authorization code.
*/
private String code;
/**
* Linkedin app.
*/
private String lapp;
/**
* Linkedin key.
*/
private String lkey;
/**
* Linkedin user identifier.
*/
private String identifier;
/**
* Ctor.
* @param code Linkedin authorization code.
* @param lapp Linkedin app.
* @param lkey Linkedin key.
* @param identifier Linkedin user identifier.
*/
LinkedinScript(final String code, final String lapp,
final String lkey, final String identifier) {
this.code = code;
this.lapp = lapp;
this.lkey = lkey;
this.identifier = identifier;
}
@Override
public void exec(final URI home) throws IOException {
final Identity identity = new PsLinkedin(
new Href(String.format("%s/uas/oauth2/accessToken", home)),
new Href(String.format("%s/v1/people", home)),
this.lapp,
this.lkey
).enter(new RqFake("GET", String.format("?code=%s", this.code)))
.get();
MatcherAssert.assertThat(
identity.urn(),
CoreMatchers.equalTo(
String.format("urn:linkedin:%s", this.identifier)
)
);
MatcherAssert.assertThat(
identity.properties(),
Matchers.allOf(
Matchers.hasEntry("firstname", "Frodo"),
Matchers.hasEntry("lastname", "Baggins")
)
);
}
}
}
|
src/test/java/org/takes/facets/auth/social/PsLinkedinTest.java
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Yegor Bugayenko
*
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.takes.facets.auth.social;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import javax.json.Json;
import org.apache.commons.lang.RandomStringUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.auth.Identity;
import org.takes.facets.fork.FkRegex;
import org.takes.facets.fork.TkFork;
import org.takes.http.FtRemote;
import org.takes.misc.Href;
import org.takes.rq.RqFake;
import org.takes.rq.RqHref;
import org.takes.rq.RqPrint;
import org.takes.rs.RsJson;
/**
* Test case for {@link PsLinkedin}.
* @author Dmitry Zaytsev ([email protected])
* @version $Id$
* @since 0.16
* @checkstyle MagicNumberCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle MultipleStringLiteralsCheck (500 lines)
*/
public final class PsLinkedinTest {
/**
* Field name for "First name".
*/
private static final String FIRST_NAME = "firstName";
/**
* Test value for "First name".
*/
private static final String FRODO = "Frodo";
/**
* Field name for "Last name".
*/
private static final String LAST_NAME = "lastName";
/**
* Test value for "Last name".
*/
private static final String BAGGINS = "Baggins";
/**
* Request path pattern for token endpoint.
*/
private static final String TOKEN_PATTERN = "/uas/oauth2/accessToken";
/**
* Request path pattern for people endpoint.
*/
private static final String PEOPLE_PATTERN = "/v1/people";
/**
* Linkedin authorization code.
*/
private final String code = RandomStringUtils.randomAlphanumeric(10);
/**
* Linkedin app.
*/
private final String lapp = RandomStringUtils.randomAlphanumeric(10);
/**
* Linkedin key.
*/
private final String lkey = RandomStringUtils.randomAlphanumeric(10);
/**
* Linkedin user identifier.
*/
private final String identifier = RandomStringUtils.randomAlphanumeric(10);
/**
* PsLinkedin can login.
* @throws IOException If some problem inside
*/
@Test
public void logins() throws IOException {
final Take take = new TkFork(
new FkRegex(PsLinkedinTest.TOKEN_PATTERN, new TokenTake()),
new FkRegex(PsLinkedinTest.PEOPLE_PATTERN, new PeopleTake())
);
new FtRemote(take).exec(new LinkedinScript());
}
/**
* Take that returns JSON with the authorization token.
* @author Dmitry Zaytsev ([email protected])
* @author Rui Castro ([email protected])
* @version $Id$
* @since 0.33
*/
private class TokenTake implements Take {
@Override
public Response act(final Request req) throws IOException {
MatcherAssert.assertThat(
new RqPrint(req).printBody(),
Matchers.stringContainsInOrder(
Arrays.asList(
"grant_type=authorization_code",
String.format(
"client_id=%s",
PsLinkedinTest.this.lapp
),
"redirect_uri=",
String.format(
"client_secret=%s",
PsLinkedinTest.this.lkey
),
String.format("code=%s", PsLinkedinTest.this.code)
)
)
);
MatcherAssert.assertThat(
new RqHref.Base(req).href().toString(),
Matchers.endsWith(PsLinkedinTest.TOKEN_PATTERN)
);
return new RsJson(
Json.createObjectBuilder()
.add(
"access_token",
RandomStringUtils.randomAlphanumeric(10)
).build()
);
}
}
/**
* Take that returns JSON with test user data.
* @author Dmitry Zaytsev ([email protected])
* @author Rui Castro ([email protected])
* @version $Id$
* @since 0.33
*/
private class PeopleTake implements Take {
@Override
public Response act(final Request req) throws IOException {
return new RsJson(
Json.createObjectBuilder()
.add(
"id",
PsLinkedinTest.this.identifier
).add(
PsLinkedinTest.FIRST_NAME,
PsLinkedinTest.FRODO
).add(
PsLinkedinTest.LAST_NAME,
PsLinkedinTest.BAGGINS
).build()
);
}
}
/**
* Script to test Linkedin authorization.
* @author Dmitry Zaytsev ([email protected])
* @author Rui Castro ([email protected])
* @version $Id$
* @since 0.33
*/
private class LinkedinScript implements FtRemote.Script {
@Override
public void exec(final URI home) throws IOException {
final Identity identity = new PsLinkedin(
new Href(
String.format("%s/uas/oauth2/accessToken", home)
),
new Href(String.format("%s/v1/people/", home)),
PsLinkedinTest.this.lapp,
PsLinkedinTest.this.lkey
).enter(
new RqFake(
"GET",
String.format("?code=%s", PsLinkedinTest.this.code)
)
).get();
MatcherAssert.assertThat(
identity.urn(),
CoreMatchers.equalTo(
String.format(
"urn:linkedin:%s",
PsLinkedinTest.this.identifier
)
)
);
MatcherAssert.assertThat(
identity.properties(),
Matchers.allOf(
Matchers.hasEntry(
PsLinkedinTest.FIRST_NAME,
PsLinkedinTest.FRODO
),
Matchers.hasEntry(
PsLinkedinTest.LAST_NAME,
PsLinkedinTest.BAGGINS
)
)
);
}
}
}
|
Refactored PsLinkedinTest class to implement the share nothing principle.
|
src/test/java/org/takes/facets/auth/social/PsLinkedinTest.java
|
Refactored PsLinkedinTest class to implement the share nothing principle.
|
<ide><path>rc/test/java/org/takes/facets/auth/social/PsLinkedinTest.java
<ide> public final class PsLinkedinTest {
<ide>
<ide> /**
<del> * Field name for "First name".
<del> */
<del> private static final String FIRST_NAME = "firstName";
<del>
<del> /**
<del> * Test value for "First name".
<del> */
<del> private static final String FRODO = "Frodo";
<del>
<del> /**
<del> * Field name for "Last name".
<del> */
<del> private static final String LAST_NAME = "lastName";
<del>
<del> /**
<del> * Test value for "Last name".
<del> */
<del> private static final String BAGGINS = "Baggins";
<del>
<del> /**
<del> * Request path pattern for token endpoint.
<del> */
<del> private static final String TOKEN_PATTERN = "/uas/oauth2/accessToken";
<del>
<del> /**
<del> * Request path pattern for people endpoint.
<del> */
<del> private static final String PEOPLE_PATTERN = "/v1/people";
<del>
<del> /**
<del> * Linkedin authorization code.
<del> */
<del> private final String code = RandomStringUtils.randomAlphanumeric(10);
<del>
<del> /**
<del> * Linkedin app.
<del> */
<del> private final String lapp = RandomStringUtils.randomAlphanumeric(10);
<del>
<del> /**
<del> * Linkedin key.
<del> */
<del> private final String lkey = RandomStringUtils.randomAlphanumeric(10);
<del>
<del> /**
<del> * Linkedin user identifier.
<del> */
<del> private final String identifier = RandomStringUtils.randomAlphanumeric(10);
<del>
<del> /**
<ide> * PsLinkedin can login.
<ide> * @throws IOException If some problem inside
<ide> */
<ide> @Test
<ide> public void logins() throws IOException {
<add> final String code = RandomStringUtils.randomAlphanumeric(10);
<add> final String lapp = RandomStringUtils.randomAlphanumeric(10);
<add> final String lkey = RandomStringUtils.randomAlphanumeric(10);
<add> final String identifier = RandomStringUtils.randomAlphanumeric(10);
<add> final String tokenpattern = "/uas/oauth2/accessToken";
<add> final String peoplepattern = "/v1/people";
<ide> final Take take = new TkFork(
<del> new FkRegex(PsLinkedinTest.TOKEN_PATTERN, new TokenTake()),
<del> new FkRegex(PsLinkedinTest.PEOPLE_PATTERN, new PeopleTake())
<add> new FkRegex(tokenpattern, new TokenTake(code, lapp, lkey)),
<add> new FkRegex(peoplepattern, new PeopleTake(identifier))
<ide> );
<del> new FtRemote(take).exec(new LinkedinScript());
<add> new FtRemote(take).exec(
<add> new LinkedinScript(code, lapp, lkey, identifier)
<add> );
<ide> }
<ide>
<ide> /**
<ide> * @version $Id$
<ide> * @since 0.33
<ide> */
<del> private class TokenTake implements Take {
<add> private final class TokenTake implements Take {
<add>
<add> /**
<add> * Request path pattern for token endpoint.
<add> */
<add> private final String tokenpattern = "/uas/oauth2/accessToken";
<add>
<add> /**
<add> * Linkedin authorization code.
<add> */
<add> private String code;
<add>
<add> /**
<add> * Linkedin app.
<add> */
<add> private String lapp;
<add>
<add> /**
<add> * Linkedin key.
<add> */
<add> private String lkey;
<add>
<add> /**
<add> * Ctor.
<add> * @param code Linkedin authorization code.
<add> * @param lapp Linkedin app.
<add> * @param lkey Linkedin key.
<add> */
<add> TokenTake(final String code, final String lapp, final String lkey) {
<add> this.code = code;
<add> this.lapp = lapp;
<add> this.lkey = lkey;
<add> }
<ide>
<ide> @Override
<ide> public Response act(final Request req) throws IOException {
<ide> Matchers.stringContainsInOrder(
<ide> Arrays.asList(
<ide> "grant_type=authorization_code",
<del> String.format(
<del> "client_id=%s",
<del> PsLinkedinTest.this.lapp
<del> ),
<add> String.format("client_id=%s", this.lapp),
<ide> "redirect_uri=",
<del> String.format(
<del> "client_secret=%s",
<del> PsLinkedinTest.this.lkey
<del> ),
<del> String.format("code=%s", PsLinkedinTest.this.code)
<add> String.format("client_secret=%s", this.lkey),
<add> String.format("code=%s", this.code)
<ide> )
<ide> )
<ide> );
<ide> MatcherAssert.assertThat(
<ide> new RqHref.Base(req).href().toString(),
<del> Matchers.endsWith(PsLinkedinTest.TOKEN_PATTERN)
<add> Matchers.endsWith(this.tokenpattern)
<ide> );
<ide> return new RsJson(
<ide> Json.createObjectBuilder()
<ide> * @version $Id$
<ide> * @since 0.33
<ide> */
<del> private class PeopleTake implements Take {
<add> private final class PeopleTake implements Take {
<add>
<add> /**
<add> * Linkedin user identifier.
<add> */
<add> private String identifier;
<add>
<add> /**
<add> * Ctor.
<add> * @param identifier Linkedin user identifier.
<add> */
<add> PeopleTake(final String identifier) {
<add> this.identifier = identifier;
<add> }
<ide>
<ide> @Override
<ide> public Response act(final Request req) throws IOException {
<ide> return new RsJson(
<ide> Json.createObjectBuilder()
<del> .add(
<del> "id",
<del> PsLinkedinTest.this.identifier
<del> ).add(
<del> PsLinkedinTest.FIRST_NAME,
<del> PsLinkedinTest.FRODO
<del> ).add(
<del> PsLinkedinTest.LAST_NAME,
<del> PsLinkedinTest.BAGGINS
<del> ).build()
<add> .add("id", this.identifier)
<add> .add("firstname", "Frodo")
<add> .add("lastname", "Baggins")
<add> .build()
<ide> );
<ide> }
<ide> }
<ide> * @version $Id$
<ide> * @since 0.33
<ide> */
<del> private class LinkedinScript implements FtRemote.Script {
<add> private final class LinkedinScript implements FtRemote.Script {
<add>
<add> /**
<add> * Linkedin authorization code.
<add> */
<add> private String code;
<add>
<add> /**
<add> * Linkedin app.
<add> */
<add> private String lapp;
<add>
<add> /**
<add> * Linkedin key.
<add> */
<add> private String lkey;
<add>
<add> /**
<add> * Linkedin user identifier.
<add> */
<add> private String identifier;
<add>
<add> /**
<add> * Ctor.
<add> * @param code Linkedin authorization code.
<add> * @param lapp Linkedin app.
<add> * @param lkey Linkedin key.
<add> * @param identifier Linkedin user identifier.
<add> */
<add> LinkedinScript(final String code, final String lapp,
<add> final String lkey, final String identifier) {
<add> this.code = code;
<add> this.lapp = lapp;
<add> this.lkey = lkey;
<add> this.identifier = identifier;
<add> }
<ide>
<ide> @Override
<ide> public void exec(final URI home) throws IOException {
<ide> final Identity identity = new PsLinkedin(
<del> new Href(
<del> String.format("%s/uas/oauth2/accessToken", home)
<del> ),
<del> new Href(String.format("%s/v1/people/", home)),
<del> PsLinkedinTest.this.lapp,
<del> PsLinkedinTest.this.lkey
<del> ).enter(
<del> new RqFake(
<del> "GET",
<del> String.format("?code=%s", PsLinkedinTest.this.code)
<del> )
<del> ).get();
<add> new Href(String.format("%s/uas/oauth2/accessToken", home)),
<add> new Href(String.format("%s/v1/people", home)),
<add> this.lapp,
<add> this.lkey
<add> ).enter(new RqFake("GET", String.format("?code=%s", this.code)))
<add> .get();
<ide> MatcherAssert.assertThat(
<ide> identity.urn(),
<ide> CoreMatchers.equalTo(
<del> String.format(
<del> "urn:linkedin:%s",
<del> PsLinkedinTest.this.identifier
<del> )
<add> String.format("urn:linkedin:%s", this.identifier)
<ide> )
<ide> );
<ide> MatcherAssert.assertThat(
<ide> identity.properties(),
<ide> Matchers.allOf(
<del> Matchers.hasEntry(
<del> PsLinkedinTest.FIRST_NAME,
<del> PsLinkedinTest.FRODO
<del> ),
<del> Matchers.hasEntry(
<del> PsLinkedinTest.LAST_NAME,
<del> PsLinkedinTest.BAGGINS
<del> )
<add> Matchers.hasEntry("firstname", "Frodo"),
<add> Matchers.hasEntry("lastname", "Baggins")
<ide> )
<ide> );
<ide> }
|
|
Java
|
apache-2.0
|
196bd16f02c23614d6c93f162c5e0b8e01ea5973
| 0 |
cereebro/cereebro,cereebro/cereebro,cereebro/cereebro
|
/*
* Copyright © 2017 the original authors (http://cereebro.io)
*
* 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 io.cereebro.server;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import io.cereebro.core.System;
import io.cereebro.core.SystemService;
import io.cereebro.server.graph.d3.wheel.DependencyWheel;
import io.cereebro.server.graph.sigma.Graph;
@Controller
@RequestMapping("${cereebro.server.system.path:/cereebro/system}")
public class CereebroSystemController {
private final SystemService systemService;
@Autowired
public CereebroSystemController(SystemService systemService) {
this.systemService = Objects.requireNonNull(systemService, "SystemService required");
}
@GetMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView systemPage() {
System system = systemService.get();
ModelAndView mav = new ModelAndView("cereebro/system");
mav.getModelMap().put("system", system);
Graph graph = Graph.of(system);
DependencyWheel wheel = DependencyWheel.of(system);
// Will be serialized to JSON objects by thymeleaf
mav.addObject("graph", graph);
mav.addObject("wheel", wheel);
return mav;
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public System systemJson() {
return systemService.get();
}
}
|
cereebro-server/src/main/java/io/cereebro/server/CereebroSystemController.java
|
/*
* Copyright © 2017 the original authors (http://cereebro.io)
*
* 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 io.cereebro.server;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import io.cereebro.core.System;
import io.cereebro.core.SystemService;
import io.cereebro.server.graph.d3.wheel.DependencyWheel;
import io.cereebro.server.graph.sigma.Graph;
@Controller
@RequestMapping("${cereebro.server.system.path:/cereebro/system}")
public class CereebroSystemController {
private final SystemService systemService;
@Autowired
public CereebroSystemController(SystemService systemService) {
this.systemService = Objects.requireNonNull(systemService, "SystemService required");
}
@RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView systemPage() {
System system = systemService.get();
ModelAndView mav = new ModelAndView("cereebro/system");
mav.getModelMap().put("system", system);
Graph graph = Graph.of(system);
DependencyWheel wheel = DependencyWheel.of(system);
// Will be serialized to JSON objects by thymeleaf
mav.addObject("graph", graph);
mav.addObject("wheel", wheel);
return mav;
}
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public System systemJson() {
return systemService.get();
}
}
|
Use GetMapping instead of RequestMapping
|
cereebro-server/src/main/java/io/cereebro/server/CereebroSystemController.java
|
Use GetMapping instead of RequestMapping
|
<ide><path>ereebro-server/src/main/java/io/cereebro/server/CereebroSystemController.java
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.stereotype.Controller;
<add>import org.springframework.web.bind.annotation.GetMapping;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<del>import org.springframework.web.bind.annotation.RequestMethod;
<ide> import org.springframework.web.bind.annotation.ResponseBody;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide>
<ide> this.systemService = Objects.requireNonNull(systemService, "SystemService required");
<ide> }
<ide>
<del> @RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
<add> @GetMapping(produces = MediaType.TEXT_HTML_VALUE)
<ide> public ModelAndView systemPage() {
<ide> System system = systemService.get();
<ide> ModelAndView mav = new ModelAndView("cereebro/system");
<ide> return mav;
<ide> }
<ide>
<del> @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
<add> @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
<ide> @ResponseBody
<ide> public System systemJson() {
<ide> return systemService.get();
|
|
Java
|
apache-2.0
|
5bf4a385e9ebf7b853302d96356480fdf1efd96b
| 0 |
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
|
/*
* #%L
* %%
* Copyright (C) 2020 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
package io.joynr.messaging.mqtt.hivemq.client;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.Optional;
import java.util.OptionalLong;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.hivemq.client.internal.mqtt.message.publish.MqttPublish;
import com.hivemq.client.internal.mqtt.message.publish.MqttPublishResult.MqttQos1Result;
import com.hivemq.client.mqtt.datatypes.MqttTopic;
import com.hivemq.client.mqtt.MqttClientState;
import com.hivemq.client.mqtt.MqttGlobalPublishFilter;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.exceptions.MqttClientStateException;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5ClientConfig;
import com.hivemq.client.mqtt.mqtt5.Mqtt5RxClient;
import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect;
import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck;
import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish;
import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PublishResult;
import io.joynr.exceptions.JoynrDelayMessageException;
import io.joynr.messaging.FailureAction;
import io.joynr.messaging.SuccessAction;
import io.joynr.messaging.mqtt.IMqttMessagingSkeleton;
import io.joynr.statusmetrics.ConnectionStatusMetricsImpl;
import io.reactivex.Flowable;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
public class HivemqMqttClientTest {
private static final long NOT_CONNECTED_RETRY_INTERVAL_MS = 5000;
HivemqMqttClient client;
@Mock
private Mqtt5RxClient mockRxClient;
@Mock
private Mqtt5AsyncClient mockAsyncClient;
private final int defaultKeepAliveTimerSec = 30;
private final boolean defaultCleanSession = false;
private final int defaultConnectionTimeoutSec = 60;
private final int defaultReconnectDelayMs = 1000;
private final String defaultGbid = "HivemqMqttClientTest-GBID";
@Mock
private Mqtt5ClientConfig mockClientConfig;
@Mock
private Flowable<Mqtt5Publish> mockPublishesFlowable;
@Captor
ArgumentCaptor<Consumer<? super Mqtt5Publish>> publishesFlowableOnNextCaptor;
@Captor
ArgumentCaptor<Consumer<? super Throwable>> publishesFlowableOnErrorCaptor;
@Mock
private IMqttMessagingSkeleton mockSkeleton;
@Mock
private SuccessAction mockSuccessAction;
@Mock
private FailureAction mockFailureAction;
@Mock
private Single<Mqtt5ConnAck> mockConnectSingle;
private String testTopic;
private byte[] testPayload;
private long testExpiryIntervalSec;
private CompletableFuture<Mqtt5PublishResult> publishFuture;
@Mock
private ConnectionStatusMetricsImpl mockConnectionStatusMetrics;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
testTopic = this.getClass().getName() + "-topic-" + System.currentTimeMillis();
testPayload = (this.getClass().getName() + "-payload-" + System.currentTimeMillis()).getBytes();
testExpiryIntervalSec = 60;
publishFuture = new CompletableFuture<Mqtt5PublishResult>();
doReturn(mockClientConfig).when(mockRxClient).getConfig();
doReturn(mockPublishesFlowable).when(mockRxClient).publishes(eq(MqttGlobalPublishFilter.ALL));
doReturn(mockAsyncClient).when(mockRxClient).toAsync();
doReturn(publishFuture).when(mockAsyncClient).publish(any(Mqtt5Publish.class));
createDefaultClient();
}
private void createDefaultClient() {
client = new HivemqMqttClient(mockRxClient,
defaultKeepAliveTimerSec,
defaultCleanSession,
defaultConnectionTimeoutSec,
defaultReconnectDelayMs,
true,
true,
defaultGbid,
mockConnectionStatusMetrics);
}
@Test
public void publishMessage_callsSuccessActionOnSuccess() {
Mqtt5Publish expectedPublish = Mqtt5Publish.builder()
.topic(testTopic)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(testPayload)
.messageExpiryInterval(testExpiryIntervalSec)
.build();
MqttQos1Result mockResult = new MqttQos1Result((MqttPublish) expectedPublish, null, null);
doReturn(MqttClientState.CONNECTED).when(mockClientConfig).getState();
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
verify(mockSuccessAction, times(0)).execute();
verify(mockAsyncClient, times(1)).publish(expectedPublish);
publishFuture.complete(mockResult);
verify(mockSuccessAction, times(1)).execute();
verify(mockConnectionStatusMetrics, times(1)).increaseSentMessages();
verify(mockFailureAction, times(0)).execute(any(Throwable.class));
}
private void testPublishMessageDoesNotPublishAndCallsFailureAction() {
JoynrDelayMessageException expectedException = new JoynrDelayMessageException(NOT_CONNECTED_RETRY_INTERVAL_MS,
"Publish failed: Mqtt client not connected.");
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockFailureAction, times(1)).execute(eq(expectedException));
verify(mockSuccessAction, times(0)).execute();
verify(mockAsyncClient, times(0)).publish(any(Mqtt5Publish.class));
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_DISCONNECTED() {
doReturn(MqttClientState.DISCONNECTED).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_CONNECTING() {
doReturn(MqttClientState.CONNECTING).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_CONNECTING_RECONNECT() {
doReturn(MqttClientState.CONNECTING_RECONNECT).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_DISCONNECTED_RECONNECT() {
doReturn(MqttClientState.DISCONNECTED_RECONNECT).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
private void testPublishMessageWithException(Exception publishException, Exception expectedException) {
Mqtt5Publish expectedPublish = Mqtt5Publish.builder()
.topic(testTopic)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(testPayload)
.messageExpiryInterval(testExpiryIntervalSec)
.build();
doReturn(MqttClientState.CONNECTED).when(mockClientConfig).getState();
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockFailureAction, times(0)).execute(any(Throwable.class));
verify(mockAsyncClient, times(1)).publish(expectedPublish);
publishFuture.completeExceptionally(publishException);
verify(mockSuccessAction, times(0)).execute();
verify(mockFailureAction, times(1)).execute(eq(expectedException));
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
}
@Test
public void publishMessage_callsFailureActionOnMqttClientStateException() {
MqttClientStateException publishException = new MqttClientStateException("test exception");
JoynrDelayMessageException expectedException = new JoynrDelayMessageException(NOT_CONNECTED_RETRY_INTERVAL_MS,
"Publish failed: "
+ publishException.toString());
testPublishMessageWithException(publishException, expectedException);
}
@Test
public void publishMessage_callsFailureActionOnOtherError() {
Exception publishException = new Exception("test exception");
JoynrDelayMessageException expectedException = new JoynrDelayMessageException("Publish failed: "
+ publishException.toString());
testPublishMessageWithException(publishException, expectedException);
}
@Test
public void publishMessage_callsFailureActionOnErrorResult() {
Exception publishException = new Exception("test exception");
JoynrDelayMessageException expectedException = new JoynrDelayMessageException("Publish failed: "
+ publishException.toString());
Mqtt5Publish expectedPublish = Mqtt5Publish.builder()
.topic(testTopic)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(testPayload)
.messageExpiryInterval(testExpiryIntervalSec)
.build();
MqttQos1Result mockResult = new MqttQos1Result((MqttPublish) expectedPublish, publishException, null);
doReturn(MqttClientState.CONNECTED).when(mockClientConfig).getState();
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockFailureAction, times(0)).execute(any(Throwable.class));
verify(mockAsyncClient, times(1)).publish(expectedPublish);
publishFuture.complete(mockResult);
verify(mockSuccessAction, times(0)).execute();
verify(mockFailureAction, times(1)).execute(eq(expectedException));
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
}
@Test
public void incomingMessageIncreasesReceivedMessagesCount() throws Exception {
// Capturing the real publishes Consumers did not work because verify() with ArgumentCaptor calls
// the real implementation with null values which is not allowed:
// java.lang.NullPointerException: onNext is null
// at io.reactivex.internal.functions.ObjectHelper.requireNonNull(ObjectHelper.java)
// at io.reactivex.Flowable.subscribe(Flowable.java)
// at io.reactivex.Flowable.subscribe(Flowable.java)
// at io.joynr.messaging.mqtt.hivemq.client.HivemqMqttClientTest.incomingMessageIncreasesReceivedMessagesCount
// verify(mockPublishesFlowable).subscribe(publishesFlowableOnNextCaptor.capture(), publishesFlowableOnErrorCaptor.capture());
// publishesFlowableOnNextCaptor.getValue().accept(mockPublish);
client.setMessageListener(mockSkeleton);
verify(mockConnectionStatusMetrics, times(0)).increaseReceivedMessages();
Mqtt5Publish mockPublish = mock(Mqtt5Publish.class);
doReturn(new byte[0]).when(mockPublish).getPayloadAsBytes();
Optional<ByteBuffer> optionalByteBuffer = Optional.ofNullable(null);
doReturn(optionalByteBuffer).when(mockPublish).getPayload();
doReturn(MqttTopic.of("topic")).when(mockPublish).getTopic();
doReturn(false).when(mockPublish).isRetain();
doReturn(null).when(mockPublish).getQos();
doReturn(OptionalLong.of(0l)).when(mockPublish).getMessageExpiryInterval();
Method handleIncomingMessage = client.getClass().getDeclaredMethod("handleIncomingMessage", Mqtt5Publish.class);
handleIncomingMessage.setAccessible(true);
handleIncomingMessage.invoke(client, mockPublish);
verify(mockConnectionStatusMetrics, times(1)).increaseReceivedMessages();
}
@Test
public void startIncreasesNumberOfConnectionAttempts() {
doAnswer(new Answer<MqttClientState>() {
int callCount = 0;
@Override
public MqttClientState answer(InvocationOnMock invocation) throws Throwable {
if (callCount < 2) {
callCount++;
return MqttClientState.DISCONNECTED;
}
return MqttClientState.CONNECTED;
}
}).when(mockClientConfig).getState();
client.setMessageListener(mockSkeleton);
verify(mockConnectionStatusMetrics, times(0)).increaseConnectionAttempts();
// Mocking the connect behavior did not work because doReturn() calls the real implementation of timeout():
// java.lang.NullPointerException: unit is null
// at io.reactivex.internal.functions.ObjectHelper.requireNonNull(ObjectHelper.java)
// at io.reactivex.Single.timeout0(Single.java)
// at io.reactivex.Single.timeout(Single.java)
// at io.joynr.messaging.mqtt.hivemq.client.HivemqMqttClientTest.startIncreasesNumberOfConnectionAttempts
// doReturn(mockConnectSingle).when(mockRxClient).connect(any(Mqtt5Connect.class));
// doReturn(mockConnectSingle).when(mockConnectSingle).timeout(anyLong(), any(TimeUnit.class));
// doReturn(mockConnectSingle).when(mockConnectSingle).doOnSuccess(Matchers.<Consumer<? super Mqtt5ConnAck>>any());
doThrow(new RuntimeException()).when(mockRxClient).connect(any(Mqtt5Connect.class));
client.start();
verify(mockConnectionStatusMetrics, times(1)).increaseConnectionAttempts();
}
}
|
java/messaging/mqtt/hivemq-mqtt-client/src/test/java/io/joynr/messaging/mqtt/hivemq/client/HivemqMqttClientTest.java
|
/*
* #%L
* %%
* Copyright (C) 2020 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
package io.joynr.messaging.mqtt.hivemq.client;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.lang.reflect.Method;
import java.util.concurrent.CompletableFuture;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.hivemq.client.internal.mqtt.message.publish.MqttPublish;
import com.hivemq.client.internal.mqtt.message.publish.MqttPublishResult.MqttQos1Result;
import com.hivemq.client.mqtt.MqttClientState;
import com.hivemq.client.mqtt.MqttGlobalPublishFilter;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.exceptions.MqttClientStateException;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5ClientConfig;
import com.hivemq.client.mqtt.mqtt5.Mqtt5RxClient;
import com.hivemq.client.mqtt.mqtt5.message.connect.Mqtt5Connect;
import com.hivemq.client.mqtt.mqtt5.message.connect.connack.Mqtt5ConnAck;
import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5Publish;
import com.hivemq.client.mqtt.mqtt5.message.publish.Mqtt5PublishResult;
import io.joynr.exceptions.JoynrDelayMessageException;
import io.joynr.messaging.FailureAction;
import io.joynr.messaging.SuccessAction;
import io.joynr.messaging.mqtt.IMqttMessagingSkeleton;
import io.joynr.statusmetrics.ConnectionStatusMetricsImpl;
import io.reactivex.Flowable;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
public class HivemqMqttClientTest {
private static final long NOT_CONNECTED_RETRY_INTERVAL_MS = 5000;
HivemqMqttClient client;
@Mock
private Mqtt5RxClient mockRxClient;
@Mock
private Mqtt5AsyncClient mockAsyncClient;
private final int defaultKeepAliveTimerSec = 30;
private final boolean defaultCleanSession = false;
private final int defaultConnectionTimeoutSec = 60;
private final int defaultReconnectDelayMs = 1000;
private final String defaultGbid = "HivemqMqttClientTest-GBID";
@Mock
private Mqtt5ClientConfig mockClientConfig;
@Mock
private Flowable<Mqtt5Publish> mockPublishesFlowable;
@Captor
ArgumentCaptor<Consumer<? super Mqtt5Publish>> publishesFlowableOnNextCaptor;
@Captor
ArgumentCaptor<Consumer<? super Throwable>> publishesFlowableOnErrorCaptor;
@Mock
private IMqttMessagingSkeleton mockSkeleton;
@Mock
private SuccessAction mockSuccessAction;
@Mock
private FailureAction mockFailureAction;
@Mock
private Single<Mqtt5ConnAck> mockConnectSingle;
private String testTopic;
private byte[] testPayload;
private long testExpiryIntervalSec;
private CompletableFuture<Mqtt5PublishResult> publishFuture;
@Mock
private ConnectionStatusMetricsImpl mockConnectionStatusMetrics;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
testTopic = this.getClass().getName() + "-topic-" + System.currentTimeMillis();
testPayload = (this.getClass().getName() + "-payload-" + System.currentTimeMillis()).getBytes();
testExpiryIntervalSec = 60;
publishFuture = new CompletableFuture<Mqtt5PublishResult>();
doReturn(mockClientConfig).when(mockRxClient).getConfig();
doReturn(mockPublishesFlowable).when(mockRxClient).publishes(eq(MqttGlobalPublishFilter.ALL));
doReturn(mockAsyncClient).when(mockRxClient).toAsync();
doReturn(publishFuture).when(mockAsyncClient).publish(any(Mqtt5Publish.class));
createDefaultClient();
}
private void createDefaultClient() {
client = new HivemqMqttClient(mockRxClient,
defaultKeepAliveTimerSec,
defaultCleanSession,
defaultConnectionTimeoutSec,
defaultReconnectDelayMs,
true,
true,
defaultGbid,
mockConnectionStatusMetrics);
}
@Test
public void publishMessage_callsSuccessActionOnSuccess() {
Mqtt5Publish expectedPublish = Mqtt5Publish.builder()
.topic(testTopic)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(testPayload)
.messageExpiryInterval(testExpiryIntervalSec)
.build();
MqttQos1Result mockResult = new MqttQos1Result((MqttPublish) expectedPublish, null, null);
doReturn(MqttClientState.CONNECTED).when(mockClientConfig).getState();
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
verify(mockSuccessAction, times(0)).execute();
verify(mockAsyncClient, times(1)).publish(expectedPublish);
publishFuture.complete(mockResult);
verify(mockSuccessAction, times(1)).execute();
verify(mockConnectionStatusMetrics, times(1)).increaseSentMessages();
verify(mockFailureAction, times(0)).execute(any(Throwable.class));
}
private void testPublishMessageDoesNotPublishAndCallsFailureAction() {
JoynrDelayMessageException expectedException = new JoynrDelayMessageException(NOT_CONNECTED_RETRY_INTERVAL_MS,
"Publish failed: Mqtt client not connected.");
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockFailureAction, times(1)).execute(eq(expectedException));
verify(mockSuccessAction, times(0)).execute();
verify(mockAsyncClient, times(0)).publish(any(Mqtt5Publish.class));
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_DISCONNECTED() {
doReturn(MqttClientState.DISCONNECTED).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_CONNECTING() {
doReturn(MqttClientState.CONNECTING).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_CONNECTING_RECONNECT() {
doReturn(MqttClientState.CONNECTING_RECONNECT).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
@Test
public void publishMessage_doesNotPublishAndCallsFailureActionIfNotConnected_DISCONNECTED_RECONNECT() {
doReturn(MqttClientState.DISCONNECTED_RECONNECT).when(mockClientConfig).getState();
testPublishMessageDoesNotPublishAndCallsFailureAction();
}
private void testPublishMessageWithException(Exception publishException, Exception expectedException) {
Mqtt5Publish expectedPublish = Mqtt5Publish.builder()
.topic(testTopic)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(testPayload)
.messageExpiryInterval(testExpiryIntervalSec)
.build();
doReturn(MqttClientState.CONNECTED).when(mockClientConfig).getState();
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockFailureAction, times(0)).execute(any(Throwable.class));
verify(mockAsyncClient, times(1)).publish(expectedPublish);
publishFuture.completeExceptionally(publishException);
verify(mockSuccessAction, times(0)).execute();
verify(mockFailureAction, times(1)).execute(eq(expectedException));
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
}
@Test
public void publishMessage_callsFailureActionOnMqttClientStateException() {
MqttClientStateException publishException = new MqttClientStateException("test exception");
JoynrDelayMessageException expectedException = new JoynrDelayMessageException(NOT_CONNECTED_RETRY_INTERVAL_MS,
"Publish failed: "
+ publishException.toString());
testPublishMessageWithException(publishException, expectedException);
}
@Test
public void publishMessage_callsFailureActionOnOtherError() {
Exception publishException = new Exception("test exception");
JoynrDelayMessageException expectedException = new JoynrDelayMessageException("Publish failed: "
+ publishException.toString());
testPublishMessageWithException(publishException, expectedException);
}
@Test
public void publishMessage_callsFailureActionOnErrorResult() {
Exception publishException = new Exception("test exception");
JoynrDelayMessageException expectedException = new JoynrDelayMessageException("Publish failed: "
+ publishException.toString());
Mqtt5Publish expectedPublish = Mqtt5Publish.builder()
.topic(testTopic)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(testPayload)
.messageExpiryInterval(testExpiryIntervalSec)
.build();
MqttQos1Result mockResult = new MqttQos1Result((MqttPublish) expectedPublish, publishException, null);
doReturn(MqttClientState.CONNECTED).when(mockClientConfig).getState();
client.publishMessage(testTopic,
testPayload,
MqttQos.AT_LEAST_ONCE.getCode(),
testExpiryIntervalSec,
mockSuccessAction,
mockFailureAction);
verify(mockFailureAction, times(0)).execute(any(Throwable.class));
verify(mockAsyncClient, times(1)).publish(expectedPublish);
publishFuture.complete(mockResult);
verify(mockSuccessAction, times(0)).execute();
verify(mockFailureAction, times(1)).execute(eq(expectedException));
verify(mockConnectionStatusMetrics, times(0)).increaseSentMessages();
}
@Test
public void incomingMessageIncreasesReceivedMessagesCount() throws Exception {
// Capturing the real publishes Consumers did not work because verify() with ArgumentCaptor calls
// the real implementation with null values which is not allowed:
// java.lang.NullPointerException: onNext is null
// at io.reactivex.internal.functions.ObjectHelper.requireNonNull(ObjectHelper.java)
// at io.reactivex.Flowable.subscribe(Flowable.java)
// at io.reactivex.Flowable.subscribe(Flowable.java)
// at io.joynr.messaging.mqtt.hivemq.client.HivemqMqttClientTest.incomingMessageIncreasesReceivedMessagesCount
// verify(mockPublishesFlowable).subscribe(publishesFlowableOnNextCaptor.capture(), publishesFlowableOnErrorCaptor.capture());
// publishesFlowableOnNextCaptor.getValue().accept(mockPublish);
client.setMessageListener(mockSkeleton);
verify(mockConnectionStatusMetrics, times(0)).increaseReceivedMessages();
Mqtt5Publish mockPublish = mock(Mqtt5Publish.class);
doReturn(new byte[0]).when(mockPublish).getPayloadAsBytes();
Method handleIncomingMessage = client.getClass().getDeclaredMethod("handleIncomingMessage", Mqtt5Publish.class);
handleIncomingMessage.setAccessible(true);
handleIncomingMessage.invoke(client, mockPublish);
verify(mockConnectionStatusMetrics, times(1)).increaseReceivedMessages();
}
@Test
public void startIncreasesNumberOfConnectionAttempts() {
doAnswer(new Answer<MqttClientState>() {
int callCount = 0;
@Override
public MqttClientState answer(InvocationOnMock invocation) throws Throwable {
if (callCount < 2) {
callCount++;
return MqttClientState.DISCONNECTED;
}
return MqttClientState.CONNECTED;
}
}).when(mockClientConfig).getState();
client.setMessageListener(mockSkeleton);
verify(mockConnectionStatusMetrics, times(0)).increaseConnectionAttempts();
// Mocking the connect behavior did not work because doReturn() calls the real implementation of timeout():
// java.lang.NullPointerException: unit is null
// at io.reactivex.internal.functions.ObjectHelper.requireNonNull(ObjectHelper.java)
// at io.reactivex.Single.timeout0(Single.java)
// at io.reactivex.Single.timeout(Single.java)
// at io.joynr.messaging.mqtt.hivemq.client.HivemqMqttClientTest.startIncreasesNumberOfConnectionAttempts
// doReturn(mockConnectSingle).when(mockRxClient).connect(any(Mqtt5Connect.class));
// doReturn(mockConnectSingle).when(mockConnectSingle).timeout(anyLong(), any(TimeUnit.class));
// doReturn(mockConnectSingle).when(mockConnectSingle).doOnSuccess(Matchers.<Consumer<? super Mqtt5ConnAck>>any());
doThrow(new RuntimeException()).when(mockRxClient).connect(any(Mqtt5Connect.class));
client.start();
verify(mockConnectionStatusMetrics, times(1)).increaseConnectionAttempts();
}
}
|
[Java] Fixed mock of Mqtt5Publish in HivemqMqttClientTest
|
java/messaging/mqtt/hivemq-mqtt-client/src/test/java/io/joynr/messaging/mqtt/hivemq/client/HivemqMqttClientTest.java
|
[Java] Fixed mock of Mqtt5Publish in HivemqMqttClientTest
|
<ide><path>ava/messaging/mqtt/hivemq-mqtt-client/src/test/java/io/joynr/messaging/mqtt/hivemq/client/HivemqMqttClientTest.java
<ide> import static org.mockito.Mockito.verify;
<ide>
<ide> import java.lang.reflect.Method;
<add>import java.nio.ByteBuffer;
<ide> import java.util.concurrent.CompletableFuture;
<add>import java.util.Optional;
<add>import java.util.OptionalLong;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<ide> import com.hivemq.client.internal.mqtt.message.publish.MqttPublish;
<ide> import com.hivemq.client.internal.mqtt.message.publish.MqttPublishResult.MqttQos1Result;
<add>import com.hivemq.client.mqtt.datatypes.MqttTopic;
<ide> import com.hivemq.client.mqtt.MqttClientState;
<ide> import com.hivemq.client.mqtt.MqttGlobalPublishFilter;
<ide> import com.hivemq.client.mqtt.datatypes.MqttQos;
<ide>
<ide> Mqtt5Publish mockPublish = mock(Mqtt5Publish.class);
<ide> doReturn(new byte[0]).when(mockPublish).getPayloadAsBytes();
<add> Optional<ByteBuffer> optionalByteBuffer = Optional.ofNullable(null);
<add> doReturn(optionalByteBuffer).when(mockPublish).getPayload();
<add> doReturn(MqttTopic.of("topic")).when(mockPublish).getTopic();
<add> doReturn(false).when(mockPublish).isRetain();
<add> doReturn(null).when(mockPublish).getQos();
<add> doReturn(OptionalLong.of(0l)).when(mockPublish).getMessageExpiryInterval();
<ide> Method handleIncomingMessage = client.getClass().getDeclaredMethod("handleIncomingMessage", Mqtt5Publish.class);
<ide> handleIncomingMessage.setAccessible(true);
<ide> handleIncomingMessage.invoke(client, mockPublish);
|
|
Java
|
apache-2.0
|
088c14e0144f0546650bf4037c7f6d7ba68802cb
| 0 |
orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb
|
package com.orientechnologies.orient.server.distributed.impl.metadata;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.OSchemaException;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OClassEmbedded;
import com.orientechnologies.orient.core.metadata.schema.OClassImpl;
import com.orientechnologies.orient.core.metadata.schema.OGlobalProperty;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OPropertyEmbedded;
import com.orientechnologies.orient.core.metadata.schema.OPropertyImpl;
import com.orientechnologies.orient.core.metadata.schema.OSchemaShared;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.server.distributed.ODistributedConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedServerLog;
import com.orientechnologies.orient.server.distributed.ODistributedServerManager;
import com.orientechnologies.orient.server.distributed.OModifiableDistributedConfiguration;
import com.orientechnologies.orient.server.distributed.impl.ODatabaseDocumentDistributed;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
/** Created by tglman on 22/06/17. */
public class OClassDistributed extends OClassEmbedded {
private volatile int[] bestClusterIds;
private volatile int lastVersion;
protected OClassDistributed(OSchemaShared iOwner, String iName) {
super(iOwner, iName);
}
public OClassDistributed(OSchemaShared iOwner, String iName, int[] iClusterIds) {
super(iOwner, iName, iClusterIds);
}
public OClassDistributed(OSchemaShared iOwner, ODocument iDocument, String iName) {
super(iOwner, iDocument, iName);
}
@Override
protected OPropertyImpl createPropertyInstance(ODocument p) {
return new OPropertyDistributed(this, p);
}
@Override
protected OPropertyEmbedded createPropertyInstance(OGlobalProperty global) {
return new OPropertyDistributed(this, global);
}
public OProperty addProperty(
final String propertyName,
final OType type,
final OType linkedType,
final OClass linkedClass,
final boolean unsafe) {
if (type == null) throw new OSchemaException("Property type not defined.");
if (propertyName == null || propertyName.length() == 0)
throw new OSchemaException("Property name is null or empty");
final ODatabaseDocumentInternal database = getDatabase();
validatePropertyName(propertyName);
if (database.getTransaction().isActive()) {
throw new OSchemaException(
"Cannot create property '" + propertyName + "' inside a transaction");
}
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (linkedType != null) OPropertyImpl.checkLinkTypeSupport(type);
if (linkedClass != null) OPropertyImpl.checkSupportLinkedClass(type);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final StringBuilder cmd = new StringBuilder("create property ");
// CLASS.PROPERTY NAME
cmd.append('`');
cmd.append(name);
cmd.append('`');
cmd.append('.');
cmd.append('`');
cmd.append(propertyName);
cmd.append('`');
// TYPE
cmd.append(' ');
cmd.append(type.getName());
if (linkedType != null) {
// TYPE
cmd.append(' ');
cmd.append(linkedType.getName());
} else if (linkedClass != null) {
// TYPE
cmd.append(' ');
cmd.append('`');
cmd.append(linkedClass.getName());
cmd.append('`');
}
if (unsafe) cmd.append(" unsafe ");
owner.sendCommand(database, cmd.toString());
} else
return (OProperty)
OScenarioThreadLocal.executeAsDistributed(
(Callable<OProperty>)
() -> addPropertyInternal(propertyName, type, linkedType, linkedClass, unsafe));
} finally {
releaseSchemaWriteLock();
}
return getProperty(propertyName);
}
public OClassImpl setEncryption(final String iValue) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` encryption %s", name, iValue);
owner.sendCommand(database, cmd);
} else setEncryptionInternal(database, iValue);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass setClusterSelection(final String value) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` clusterselection '%s'", name, value);
owner.sendCommand(database, cmd);
} else setClusterSelectionInternal(value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public OClassImpl setCustom(final String name, final String value) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` custom `%s`='%s'", getName(), name, value);
owner.sendCommand(database, cmd);
} else setCustomInternal(name, value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public void clearCustom() {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` custom clear", getName());
owner.sendCommand(database, cmd);
} else clearCustomInternal();
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass setSuperClasses(final List<? extends OClass> classes) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (classes != null) {
List<OClass> toCheck = new ArrayList<OClass>(classes);
toCheck.add(this);
checkParametersConflict(toCheck);
}
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final StringBuilder sb = new StringBuilder();
if (classes != null && classes.size() > 0) {
for (OClass superClass : classes) {
sb.append('`').append(superClass.getName()).append("`,");
}
sb.deleteCharAt(sb.length() - 1);
} else sb.append("null");
final String cmd = String.format("alter class `%s` superclasses %s", name, sb);
owner.sendCommand(database, cmd);
} else setSuperClassesInternal(classes);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass addSuperClass(final OClass superClass) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
checkParametersConflict(superClass);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd =
String.format(
"alter class `%s` superclass +`%s`",
name, superClass != null ? superClass.getName() : null);
owner.sendCommand(database, cmd);
} else addSuperClassInternal(database, superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass removeSuperClass(OClass superClass) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd =
String.format(
"alter class `%s` superclass -`%s`",
name, superClass != null ? superClass.getName() : null);
owner.sendCommand(database, cmd);
} else removeSuperClassInternal(superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setName(final String name) {
if (getName().equals(name)) return this;
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(name);
OClass oClass = database.getMetadata().getSchema().getClass(name);
if (oClass != null) {
String error =
String.format(
"Cannot rename class %s to %s. A Class with name %s exists", this.name, name, name);
throw new OSchemaException(error);
}
if (wrongCharacter != null)
throw new OSchemaException(
"Invalid class name found. Character '"
+ wrongCharacter
+ "' cannot be used in class name '"
+ name
+ "'");
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` name `%s`", this.name, name);
owner.sendCommand(database, cmd);
} else setNameInternal(database, name);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setShortName(String shortName) {
if (shortName != null) {
shortName = shortName.trim();
if (shortName.isEmpty()) shortName = null;
}
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` shortname `%s`", name, shortName);
owner.sendCommand(database, cmd);
} else setShortNameInternal(database, shortName);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass truncateCluster(String clusterName) {
getDatabase().checkSecurity(ORule.ResourceGeneric.CLASS, ORole.PERMISSION_DELETE, name);
acquireSchemaReadLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
if (isDistributedCommand(database)) {
final String cmd = String.format("truncate cluster %s", clusterName);
owner.sendCommand(database, cmd);
} else truncateClusterInternal(clusterName, database);
} finally {
releaseSchemaReadLock();
}
return this;
}
public OClass setStrictMode(final boolean isStrict) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` strictmode %s", name, isStrict);
owner.sendCommand(database, cmd);
} else setStrictModeInternal(isStrict);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setDescription(String iDescription) {
if (iDescription != null) {
iDescription = iDescription.trim();
if (iDescription.isEmpty()) iDescription = null;
}
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` description ?", name);
owner.sendCommand(database, cmd);
} else setDescriptionInternal(iDescription);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass addClusterId(final int clusterId) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` addcluster %d", name, clusterId);
owner.sendCommand(database, cmd);
} else addClusterIdInternal(database, clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass removeClusterId(final int clusterId) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (clusterIds.length == 1 && clusterId == clusterIds[0])
throw new ODatabaseException(
" Impossible to remove the last cluster of class '"
+ getName()
+ "' drop the class instead");
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` removecluster %d", name, clusterId);
owner.sendCommand(database, cmd);
} else removeClusterIdInternal(database, clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public void dropProperty(final String propertyName) {
final ODatabaseDocumentInternal database = getDatabase();
if (database.getTransaction().isActive())
throw new IllegalStateException("Cannot drop a property inside a transaction");
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE);
acquireSchemaWriteLock();
try {
if (!properties.containsKey(propertyName))
throw new OSchemaException(
"Property '" + propertyName + "' not found in class " + name + "'");
if (isDistributedCommand(database)) {
owner.sendCommand(database, "drop property " + name + '.' + propertyName);
} else
OScenarioThreadLocal.executeAsDistributed(
(Callable<OProperty>)
() -> {
dropPropertyInternal(database, propertyName);
return null;
});
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass addCluster(final String clusterNameOrId) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` addcluster `%s`", name, clusterNameOrId);
owner.sendCommand(database, cmd);
} else {
final int clusterId = owner.createClusterIfNeeded(database, clusterNameOrId);
addClusterIdInternal(database, clusterId);
}
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setOverSize(final float overSize) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
// FORMAT FLOAT LOCALE AGNOSTIC
final String cmd =
String.format("alter class `%s` oversize %s", name, new Float(overSize).toString());
owner.sendCommand(database, cmd);
} else setOverSizeInternal(database, overSize);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setAbstract(boolean isAbstract) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` abstract %s", name, isAbstract);
owner.sendCommand(database, cmd);
} else setAbstractInternal(database, isAbstract);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public int getClusterForNewInstance(ODocument doc) {
return getClusterForNewInstance((ODatabaseDocumentDistributed) getDatabase(), doc);
}
public int getClusterForNewInstance(ODatabaseDocumentDistributed db, ODocument doc) {
ODistributedServerManager manager = db.getDistributedManager();
if (bestClusterIds == null) readConfiguration(db, manager);
else {
ODistributedConfiguration cfg = manager.getDatabaseConfiguration(db.getName());
if (lastVersion != cfg.getVersion()) {
// DISTRIBUTED CFG IS CHANGED: GET BEST CLUSTER AGAIN
readConfiguration(db, manager);
ODistributedServerLog.info(
this,
manager.getLocalNodeName(),
null,
ODistributedServerLog.DIRECTION.NONE,
"New cluster list for class '%s': %s (dCfgVersion=%d)",
getName(),
Arrays.toString(bestClusterIds),
lastVersion);
}
}
final int size = bestClusterIds.length;
if (size == 0) return -1;
if (size == 1)
// ONLY ONE: RETURN IT
return bestClusterIds[0];
final int cluster = super.getClusterSelection().getCluster(this, bestClusterIds, doc);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(
this,
manager.getLocalNodeName(),
null,
ODistributedServerLog.DIRECTION.NONE,
"Selected cluster %d for class '%s' from %s (threadId=%d dCfgVersion=%d)",
cluster,
getName(),
Arrays.toString(bestClusterIds),
Thread.currentThread().getId(),
lastVersion);
return cluster;
}
public ODistributedConfiguration readConfiguration(
ODatabaseDocumentDistributed db, ODistributedServerManager manager) {
if (isAbstract())
throw new IllegalArgumentException("Cannot create a new instance of abstract class");
int[] clusterIds = getClusterIds();
final List<String> clusterNames = new ArrayList<String>(clusterIds.length);
for (int c : clusterIds) clusterNames.add(db.getClusterNameById(c).toLowerCase(Locale.ENGLISH));
ODistributedConfiguration cfg = manager.getDatabaseConfiguration(db.getName());
List<String> bestClusters =
cfg.getOwnedClustersByServer(clusterNames, manager.getLocalNodeName());
if (bestClusters.isEmpty()) {
// REBALANCE THE CLUSTERS
final OModifiableDistributedConfiguration modifiableCfg = cfg.modify();
manager.reassignClustersOwnership(
manager.getLocalNodeName(), db.getName(), modifiableCfg, true);
cfg = modifiableCfg;
// RELOAD THE CLUSTER LIST TO GET THE NEW CLUSTER CREATED (IF ANY)
db.activateOnCurrentThread();
clusterNames.clear();
clusterIds = getClusterIds();
for (int c : clusterIds)
clusterNames.add(db.getClusterNameById(c).toLowerCase(Locale.ENGLISH));
bestClusters = cfg.getOwnedClustersByServer(clusterNames, manager.getLocalNodeName());
if (bestClusters.isEmpty()) {
// FILL THE MAP CLUSTER/SERVERS
final StringBuilder buffer = new StringBuilder();
for (String c : clusterNames) {
if (buffer.length() > 0) buffer.append(" ");
buffer.append(" ");
buffer.append(c);
buffer.append(":");
buffer.append(cfg.getServers(c, null));
}
ODistributedServerLog.warn(
this,
manager.getLocalNodeName(),
null,
ODistributedServerLog.DIRECTION.NONE,
"Cannot find best cluster for class '%s'. Configured servers for clusters %s are %s (dCfgVersion=%d)",
getName(),
clusterNames,
buffer.toString(),
cfg.getVersion());
throw new ODatabaseException(
"Cannot find best cluster for class '"
+ getName()
+ "' on server '"
+ manager.getLocalNodeName()
+ "' (clusterStrategy="
+ getName()
+ " dCfgVersion="
+ cfg.getVersion()
+ ")");
}
}
db.activateOnCurrentThread();
final int[] newBestClusters = new int[bestClusters.size()];
int i = 0;
for (String c : bestClusters) newBestClusters[i++] = db.getClusterIdByName(c);
this.bestClusterIds = newBestClusters;
lastVersion = cfg.getVersion();
return cfg;
}
protected boolean isDistributedCommand(ODatabaseDocumentInternal database) {
return !database.isLocalEnv();
}
}
|
distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/metadata/OClassDistributed.java
|
package com.orientechnologies.orient.server.distributed.impl.metadata;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.OSchemaException;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OClassEmbedded;
import com.orientechnologies.orient.core.metadata.schema.OClassImpl;
import com.orientechnologies.orient.core.metadata.schema.OGlobalProperty;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OPropertyEmbedded;
import com.orientechnologies.orient.core.metadata.schema.OPropertyImpl;
import com.orientechnologies.orient.core.metadata.schema.OSchemaShared;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.server.distributed.ODistributedConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedServerLog;
import com.orientechnologies.orient.server.distributed.ODistributedServerManager;
import com.orientechnologies.orient.server.distributed.OModifiableDistributedConfiguration;
import com.orientechnologies.orient.server.distributed.impl.ODatabaseDocumentDistributed;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
/** Created by tglman on 22/06/17. */
public class OClassDistributed extends OClassEmbedded {
private volatile int[] bestClusterIds;
private volatile int lastVersion;
protected OClassDistributed(OSchemaShared iOwner, String iName) {
super(iOwner, iName);
}
public OClassDistributed(OSchemaShared iOwner, String iName, int[] iClusterIds) {
super(iOwner, iName, iClusterIds);
}
public OClassDistributed(OSchemaShared iOwner, ODocument iDocument, String iName) {
super(iOwner, iDocument, iName);
}
@Override
protected OPropertyImpl createPropertyInstance(ODocument p) {
return new OPropertyDistributed(this, p);
}
@Override
protected OPropertyEmbedded createPropertyInstance(OGlobalProperty global) {
return new OPropertyDistributed(this, global);
}
public OProperty addProperty(
final String propertyName,
final OType type,
final OType linkedType,
final OClass linkedClass,
final boolean unsafe) {
if (type == null) throw new OSchemaException("Property type not defined.");
if (propertyName == null || propertyName.length() == 0)
throw new OSchemaException("Property name is null or empty");
final ODatabaseDocumentInternal database = getDatabase();
validatePropertyName(propertyName);
if (database.getTransaction().isActive()) {
throw new OSchemaException(
"Cannot create property '" + propertyName + "' inside a transaction");
}
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (linkedType != null) OPropertyImpl.checkLinkTypeSupport(type);
if (linkedClass != null) OPropertyImpl.checkSupportLinkedClass(type);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final StringBuilder cmd = new StringBuilder("create property ");
// CLASS.PROPERTY NAME
cmd.append('`');
cmd.append(name);
cmd.append('`');
cmd.append('.');
cmd.append('`');
cmd.append(propertyName);
cmd.append('`');
// TYPE
cmd.append(' ');
cmd.append(type.getName());
if (linkedType != null) {
// TYPE
cmd.append(' ');
cmd.append(linkedType.getName());
} else if (linkedClass != null) {
// TYPE
cmd.append(' ');
cmd.append('`');
cmd.append(linkedClass.getName());
cmd.append('`');
}
if (unsafe) cmd.append(" unsafe ");
owner.sendCommand(database, cmd.toString());
} else
return (OProperty)
OScenarioThreadLocal.executeAsDistributed(
(Callable<OProperty>)
() -> addPropertyInternal(propertyName, type, linkedType, linkedClass, unsafe));
} finally {
releaseSchemaWriteLock();
}
return getProperty(propertyName);
}
public OClassImpl setEncryption(final String iValue) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` encryption %s", name, iValue);
owner.sendCommand(database, cmd);
} else setEncryptionInternal(database, iValue);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass setClusterSelection(final String value) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` clusterselection '%s'", name, value);
owner.sendCommand(database, cmd);
} else setClusterSelectionInternal(value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public OClassImpl setCustom(final String name, final String value) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` custom `%s`=%s", getName(), name, value);
owner.sendCommand(database, cmd);
} else setCustomInternal(name, value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public void clearCustom() {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` custom clear", getName());
owner.sendCommand(database, cmd);
} else clearCustomInternal();
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass setSuperClasses(final List<? extends OClass> classes) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (classes != null) {
List<OClass> toCheck = new ArrayList<OClass>(classes);
toCheck.add(this);
checkParametersConflict(toCheck);
}
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final StringBuilder sb = new StringBuilder();
if (classes != null && classes.size() > 0) {
for (OClass superClass : classes) {
sb.append('`').append(superClass.getName()).append("`,");
}
sb.deleteCharAt(sb.length() - 1);
} else sb.append("null");
final String cmd = String.format("alter class `%s` superclasses %s", name, sb);
owner.sendCommand(database, cmd);
} else setSuperClassesInternal(classes);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass addSuperClass(final OClass superClass) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
checkParametersConflict(superClass);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd =
String.format(
"alter class `%s` superclass +`%s`",
name, superClass != null ? superClass.getName() : null);
owner.sendCommand(database, cmd);
} else addSuperClassInternal(database, superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass removeSuperClass(OClass superClass) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd =
String.format(
"alter class `%s` superclass -`%s`",
name, superClass != null ? superClass.getName() : null);
owner.sendCommand(database, cmd);
} else removeSuperClassInternal(superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setName(final String name) {
if (getName().equals(name)) return this;
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(name);
OClass oClass = database.getMetadata().getSchema().getClass(name);
if (oClass != null) {
String error =
String.format(
"Cannot rename class %s to %s. A Class with name %s exists", this.name, name, name);
throw new OSchemaException(error);
}
if (wrongCharacter != null)
throw new OSchemaException(
"Invalid class name found. Character '"
+ wrongCharacter
+ "' cannot be used in class name '"
+ name
+ "'");
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` name `%s`", this.name, name);
owner.sendCommand(database, cmd);
} else setNameInternal(database, name);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setShortName(String shortName) {
if (shortName != null) {
shortName = shortName.trim();
if (shortName.isEmpty()) shortName = null;
}
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` shortname `%s`", name, shortName);
owner.sendCommand(database, cmd);
} else setShortNameInternal(database, shortName);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public OClass truncateCluster(String clusterName) {
getDatabase().checkSecurity(ORule.ResourceGeneric.CLASS, ORole.PERMISSION_DELETE, name);
acquireSchemaReadLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
if (isDistributedCommand(database)) {
final String cmd = String.format("truncate cluster %s", clusterName);
owner.sendCommand(database, cmd);
} else truncateClusterInternal(clusterName, database);
} finally {
releaseSchemaReadLock();
}
return this;
}
public OClass setStrictMode(final boolean isStrict) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` strictmode %s", name, isStrict);
owner.sendCommand(database, cmd);
} else setStrictModeInternal(isStrict);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setDescription(String iDescription) {
if (iDescription != null) {
iDescription = iDescription.trim();
if (iDescription.isEmpty()) iDescription = null;
}
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` description ?", name);
owner.sendCommand(database, cmd);
} else setDescriptionInternal(iDescription);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass addClusterId(final int clusterId) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` addcluster %d", name, clusterId);
owner.sendCommand(database, cmd);
} else addClusterIdInternal(database, clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass removeClusterId(final int clusterId) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (clusterIds.length == 1 && clusterId == clusterIds[0])
throw new ODatabaseException(
" Impossible to remove the last cluster of class '"
+ getName()
+ "' drop the class instead");
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` removecluster %d", name, clusterId);
owner.sendCommand(database, cmd);
} else removeClusterIdInternal(database, clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public void dropProperty(final String propertyName) {
final ODatabaseDocumentInternal database = getDatabase();
if (database.getTransaction().isActive())
throw new IllegalStateException("Cannot drop a property inside a transaction");
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE);
acquireSchemaWriteLock();
try {
if (!properties.containsKey(propertyName))
throw new OSchemaException(
"Property '" + propertyName + "' not found in class " + name + "'");
if (isDistributedCommand(database)) {
owner.sendCommand(database, "drop property " + name + '.' + propertyName);
} else
OScenarioThreadLocal.executeAsDistributed(
(Callable<OProperty>)
() -> {
dropPropertyInternal(database, propertyName);
return null;
});
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass addCluster(final String clusterNameOrId) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` addcluster `%s`", name, clusterNameOrId);
owner.sendCommand(database, cmd);
} else {
final int clusterId = owner.createClusterIfNeeded(database, clusterNameOrId);
addClusterIdInternal(database, clusterId);
}
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setOverSize(final float overSize) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
// FORMAT FLOAT LOCALE AGNOSTIC
final String cmd =
String.format("alter class `%s` oversize %s", name, new Float(overSize).toString());
owner.sendCommand(database, cmd);
} else setOverSizeInternal(database, overSize);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass setAbstract(boolean isAbstract) {
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isDistributedCommand(database)) {
final String cmd = String.format("alter class `%s` abstract %s", name, isAbstract);
owner.sendCommand(database, cmd);
} else setAbstractInternal(database, isAbstract);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public int getClusterForNewInstance(ODocument doc) {
return getClusterForNewInstance((ODatabaseDocumentDistributed) getDatabase(), doc);
}
public int getClusterForNewInstance(ODatabaseDocumentDistributed db, ODocument doc) {
ODistributedServerManager manager = db.getDistributedManager();
if (bestClusterIds == null) readConfiguration(db, manager);
else {
ODistributedConfiguration cfg = manager.getDatabaseConfiguration(db.getName());
if (lastVersion != cfg.getVersion()) {
// DISTRIBUTED CFG IS CHANGED: GET BEST CLUSTER AGAIN
readConfiguration(db, manager);
ODistributedServerLog.info(
this,
manager.getLocalNodeName(),
null,
ODistributedServerLog.DIRECTION.NONE,
"New cluster list for class '%s': %s (dCfgVersion=%d)",
getName(),
Arrays.toString(bestClusterIds),
lastVersion);
}
}
final int size = bestClusterIds.length;
if (size == 0) return -1;
if (size == 1)
// ONLY ONE: RETURN IT
return bestClusterIds[0];
final int cluster = super.getClusterSelection().getCluster(this, bestClusterIds, doc);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(
this,
manager.getLocalNodeName(),
null,
ODistributedServerLog.DIRECTION.NONE,
"Selected cluster %d for class '%s' from %s (threadId=%d dCfgVersion=%d)",
cluster,
getName(),
Arrays.toString(bestClusterIds),
Thread.currentThread().getId(),
lastVersion);
return cluster;
}
public ODistributedConfiguration readConfiguration(
ODatabaseDocumentDistributed db, ODistributedServerManager manager) {
if (isAbstract())
throw new IllegalArgumentException("Cannot create a new instance of abstract class");
int[] clusterIds = getClusterIds();
final List<String> clusterNames = new ArrayList<String>(clusterIds.length);
for (int c : clusterIds) clusterNames.add(db.getClusterNameById(c).toLowerCase(Locale.ENGLISH));
ODistributedConfiguration cfg = manager.getDatabaseConfiguration(db.getName());
List<String> bestClusters =
cfg.getOwnedClustersByServer(clusterNames, manager.getLocalNodeName());
if (bestClusters.isEmpty()) {
// REBALANCE THE CLUSTERS
final OModifiableDistributedConfiguration modifiableCfg = cfg.modify();
manager.reassignClustersOwnership(
manager.getLocalNodeName(), db.getName(), modifiableCfg, true);
cfg = modifiableCfg;
// RELOAD THE CLUSTER LIST TO GET THE NEW CLUSTER CREATED (IF ANY)
db.activateOnCurrentThread();
clusterNames.clear();
clusterIds = getClusterIds();
for (int c : clusterIds)
clusterNames.add(db.getClusterNameById(c).toLowerCase(Locale.ENGLISH));
bestClusters = cfg.getOwnedClustersByServer(clusterNames, manager.getLocalNodeName());
if (bestClusters.isEmpty()) {
// FILL THE MAP CLUSTER/SERVERS
final StringBuilder buffer = new StringBuilder();
for (String c : clusterNames) {
if (buffer.length() > 0) buffer.append(" ");
buffer.append(" ");
buffer.append(c);
buffer.append(":");
buffer.append(cfg.getServers(c, null));
}
ODistributedServerLog.warn(
this,
manager.getLocalNodeName(),
null,
ODistributedServerLog.DIRECTION.NONE,
"Cannot find best cluster for class '%s'. Configured servers for clusters %s are %s (dCfgVersion=%d)",
getName(),
clusterNames,
buffer.toString(),
cfg.getVersion());
throw new ODatabaseException(
"Cannot find best cluster for class '"
+ getName()
+ "' on server '"
+ manager.getLocalNodeName()
+ "' (clusterStrategy="
+ getName()
+ " dCfgVersion="
+ cfg.getVersion()
+ ")");
}
}
db.activateOnCurrentThread();
final int[] newBestClusters = new int[bestClusters.size()];
int i = 0;
for (String c : bestClusters) newBestClusters[i++] = db.getClusterIdByName(c);
this.bestClusterIds = newBestClusters;
lastVersion = cfg.getVersion();
return cfg;
}
protected boolean isDistributedCommand(ODatabaseDocumentInternal database) {
return !database.isLocalEnv();
}
}
|
Fixed OClass.setCustom() has no effect
Fixes #9890
|
distributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/metadata/OClassDistributed.java
|
Fixed OClass.setCustom() has no effect
|
<ide><path>istributed/src/main/java/com/orientechnologies/orient/server/distributed/impl/metadata/OClassDistributed.java
<ide> acquireSchemaWriteLock();
<ide> try {
<ide> if (isDistributedCommand(database)) {
<del> final String cmd = String.format("alter class `%s` custom `%s`=%s", getName(), name, value);
<add> final String cmd = String.format("alter class `%s` custom `%s`='%s'", getName(), name, value);
<ide> owner.sendCommand(database, cmd);
<ide> } else setCustomInternal(name, value);
<ide>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.